Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP equivalent ของ friend หรือ internal


PHP ไร้การสนับสนุนการประกาศแบบ friend สามารถจำลองได้ใน PHP5 โดยใช้เมธอด __get และ __set และตรวจสอบ backtrace สำหรับคลาส friend ที่อนุญาต แต่การเขียนโค้ดแบบนี้ถือว่า clumsy:

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);    } }