PHP 中类似 friend 或 internal 的声明
phpserver side programmingprogramming更新于 2025/7/22 9:37:17
PHP 不支持类似 friend 的声明。在 PHP5 中,可以使用 __get 和 __set 方法以及检查回溯来模拟允许的 friend 类。但这种编码方式被认为比较笨拙。 −
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);
}
}

