PHP等同于朋友或内部 [英] PHP equivalent of friend or internal

查看:60
本文介绍了PHP等同于朋友或内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php中是否有朋友"或内部"的等同词?如果不是,是否有任何模式可遵循以实现此行为?

Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?

抱歉,但是标准的Php不是我想要的.我正在寻找一些表演指导者所做的事情.

Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.

我有一些在后端进行C风格系统调用的类,并且玩杂耍已经变得很麻烦.我在对象A中有一些函数,这些函数将对象B作为参数,并且必须调用对象B中的一个方法,该方法将自身作为参数传递.最终用户可以在B中调用该方法,然后系统崩溃.

I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.

推荐答案

PHP不支持任何类似朋友的声明.可以使用PHP5的__get和__set方法并仅检查允许的朋友类的回溯来模拟此过程,尽管这样做的代码有点笨拙.

PHP doesn't support any friend-like declarations. It's possible to simulate this using the PHP5 __get and __set methods and inspecting a backtrace for only the allowed friend classes, although the code to do it is kind of clumsy.

在PHP网站上有一些示例代码和相关主题的讨论:

There's some sample code and discussion on the topic on PHP's site:

class HasFriends
{
    private $__friends = array('MyFriend', 'OtherFriend');

    public function __get($key)
    {
        $trace = debug_backtrace();
        if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) {
            return $this->$key;
        }

        // normal __get() code here

        trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR);
    }

    public function __set($key, $value)
    {
        $trace = debug_backtrace();
        if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) {
            return $this->$key = $value;
        }

        // normal __set() code here

        trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR);
    }
}

(tsteiner在nerdclub点网在bugs.php.net上证明的代码)

(Code proved by tsteiner at nerdclub dot net on bugs.php.net)

这篇关于PHP等同于朋友或内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆