好的,所以在工作中我们发现这种获取相关数据/对象的方法非常棒。
举个例子,我有这个类,里面有一些相关的对象:
class Country {
private $language; //$language will be an object of class Language
private $regions; //$regions will be an ARRAY of Region objects
//in the constructor i don't load regions or language
//magic method
public function __get($name) {
$fn_name = 'get_' . $name;
if (method_exists($this, $fn_name)) {
return $this->$fn_name();
} else {
if (property_exists($this, $name))
return $this->$name;
}
return $this->$name;
}
public function get_language () {
if (is_object($this->language)) return $this->language;
$this->language = new Language($params); //example
return $this->language;
}
public function get_regions () {
if (is_array($this->regions)) return $this->regions;
$this->regions = array();
$this->regions[] = new Region('fake');
$this->regions[] = new Region('fake2');
return $this->regions;
}
}
所以这个想法是:
我想要一个 Country 的实例,但我现在不需要它的语言和地区。
在另一种情况下,我需要它们,因此我将它们声明为属性,而魔术方法仅在第一次为我检索它们。
$country = new Country();
echo "language is". $country->language->name;
echo "this country has ". sizeof($country->regions)." regions";
这种按需方法(也避免了相关对象的嵌套循环)有名字吗?也许延迟加载属性?按需属性?