0

好的,所以在工作中我们发现这种获取相关数据/对象的方法非常棒。

举个例子,我有这个类,里面有一些相关的对象:

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";

这种按需方法(也避免了相关对象的嵌套循环)有名字吗?也许延迟加载属性按需属性?

4

1 回答 1

3

在另一种情况下,我需要它们,[...]仅在第一次为我检索它们。

初始化将是正确的措辞。这称为延迟初始化

http://en.wikipedia.org/wiki/Lazy_initialization

所以我声称它们是属性,然后魔法方法检索它们

这称为属性重载

http://php.net/__get

编辑:

我不认为有一个术语可以将两者结合起来。您可以将两者结合起来并获得类似“通过重载延迟初始化属性”的内容。

于 2011-02-09T15:15:24.740 回答