php支持像c ++一样的朋友功能吗?
答案 0 :(得分:7)
您最有可能是指类/变量范围。在php中,你有:
但不是friend
可见度。当对象的成员仅对其他扩展/继承对象可见时,使用protected
。
更多信息:
答案 1 :(得分:3)
没有。你必须公开它。
答案 2 :(得分:1)
PHP不支持任何类似朋友的声明。可以使用PHP5 __get和__set方法模拟这个并仅检查允许的朋友类的回溯,尽管执行此操作的代码有点笨拙。
在PHP网站上有关于该主题的示例代码和讨论:
班级HasFriends { 私人$ __ 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);
}
}