2015-06-19 48 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方法。