PHP 相容的 friend 或 internal


PHP 不支援 friend 宣告。你可以在 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() code goes 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 goes here
      trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR);
   }
}

更新於: 07-04-2020

256 人次瀏覽

啟動你的 事業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.