background image

PHP 中聚合对象介绍

PHP 中,我们可以把两个或更多个对象组合在一起,使结果就像是一个对象。

聚合对象并用__call()魔术方法截获对方法的调用,然后为这些调用确定相应的路线:

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() . '.';
Rasmus Lerdorf lives in Sunnyvale.

当构造每一个 Person 对象时,都会创建一个 Address 对象的技巧。当所调用的方法在
Person 中 没 有 定 义 时 , __call() 就 会 捕 获 它 们 , 在 符 合 条 件 时 , 再 用
call_user_func_array()将其分派给相应的对象来处理。

在这个技巧中,我们不能说 Person“是一个”Address,反之亦然。因此,用其中一个类
去扩展另一个类是没有任何意义的。