PHP equivalent of friend or internal

前端 未结 4 1318
野的像风
野的像风 2020-12-01 07:21

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

Edit: Sorry, but st

4条回答
  •  没有蜡笔的小新
    2020-12-01 08:13

    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.

    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);
        }
    }
    

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

提交回复
热议问题