2015-06-19 46 views
2

我有本書提供的這個例子:PHP的聚集對象,需要解釋

class Address { 
    protected $city; 

    public function setCity($city) { 
     $this -> city = $city; 
    } 

    public function getCity() { 
     return $this -> city; 
    } 
} 

class Person { 
    protected $name; 
    protected $address; 

    public function __construct() { 
     $this -> address = new Address; 
    } 

    public function setName($name) { 
     $this -> name = $name; 
    } 

    public function getName() { 
     return $this -> name; 
    } 

    public function __call($method, $arguments) { 
     if (method_exists($this -> address, $method)) { 
      return call_user_func_array(
        array($this -> address, $method), $arguments); 
     } 
    } 
} 
$rasmus=new Person; 
     $rasmus->setName('Rasmus Lerdorf'); 
     $rasmus->setCity('Sunnyvale'); 
     print $rasmus->getName().' lives in '.$rasmus->getCity().'.'; 

不過,我有問題的理解這段代碼。

他如何使用__construct來聚集對象,爲什麼他需要__call函數?

回答

2

當你創建一個新的對象始終執行__construct魔術方法,這臺新的屬性$addressAddress類的一個實例。
魔法__call每次調用人類不存在的方法類。 類沒有getCity方法。因此它會嘗試調用$address對象的相同名稱方法(getCity)。 此外,它會檢查,如果該方法在地址類存在,所以,如果你調用$rasmus->getStreet(),它不會被執行,因爲在地址類中定義沒有getStreet方法。

3

__constructPerson類的構造函數,它實例化了每個對象。

__call允許在Person類型的對象上調用setCity方法。類Person不具有名爲setCity的方法,但通過使用__call,它將該方法調用傳遞給類型爲Address$address實例變量。 Address類包含setCity的實際定義。

兩者都是PHP魔術函數: http://php.net/manual/en/language.oop5.magic.php

1

聚合對象是包含其他對象的對象。 Person類中的__construct方法創建一個Address對象,然後將其存儲爲屬性。

__call方法是一種所謂的「魔術方法」,每當在不存在的對象上調用方法時,就會發生這種方法。在您的代碼中,您正在調用$rasmus->getCity()。這個方法在Person類中不存在,所以當你嘗試調用它時,它實際上會調用__call方法。

__call方法中,代碼試圖檢測地址對象中是否存在該方法 - 如果存在,它會調用它。

因此,當您撥打$rasmus->getName()時,它正在調用Person->getName方法,但是當您撥打$rasmus->getCity()時,它實際上調用Address->getCity方法。