【发布时间】:2010-09-14 09:01:20
【问题描述】:
php 是否像 c++ 支持的那样支持友元函数?
【问题讨论】:
-
看起来没有:google.com/… 甚至维基百科似乎也没有提到它:en.wikipedia.org/wiki/Friend_function
-
找不到朋友但c++支持朋友类或函数\
标签: php
php 是否像 c++ 支持的那样支持友元函数?
【问题讨论】:
标签: php
您很可能指的是类/变量范围。在 php 中,你有:
但不是friend 可见性。当对象的成员仅对其他扩展/继承对象可见时,使用 protected。
更多信息:
【讨论】:
没有。您必须将其公开。
【讨论】:
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);
}
}
【讨论】: