PHP不支持类似朋友的声明。可以在PHP5中使用__get和__set方法并通过检查允许的朋友类的回溯来模拟它。但是这种编码实践被认为是笨拙的-class sample_friend {
private $__friends = array('My_Friend', 'Other_Friend');
public function __get($key) {
$trace = debug_backtrace();
if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) {
return $this->$key;
}
//__get()代码在这里
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;
}
//正常的__set()代码在这里
trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR);
}
}