据我了解您的问题,您想知道是否可以重载公共变量。
您已经知道 __get($name) 魔术方法,对吧?或者,也许您在谈论getName()、getAge()和 *getStatus_Indicator()*。
在任何情况下,作为公共属性,您都无法使用魔术方法。
我将仅列出它们以进行概念验证。
示例 1
<?php
class Dummy {
public $name;
public $age;
public $status_indicator;
public function __construct() {
foreach($this AS $name => $value) {
$this->$name = new LazyLoader($this, $name);
}
}
}
class LazyLoader {
protected $object;
protected $name;
public function __construct($object, $name) {
$this->object = $object;
$this->name = $name;
}
public function load() {
/* find the necessary $data somehow */
$name = $this->name;
$this->object->$name = $data;
/*
after the first call to LazyLoader::load
the property no longer points to a LazyLoad
object, but to the intended value
*/
}
public function __toString() {
return($this->load());
}
}
?>
示例 2
<?php
class LazyCollectionWrapper extends ArrayObject {
public function __construct($objects = array()) {
parent::__construct($objects);
}
public function offsetGet($offset) {
$this->collection[$offset]->lazyLoad();
return($this->collection[$offset]);
}
}
class Dummy {
public $name;
public $age;
public $status_indicator;
public function lazyLoad() {
/* load stuff here */
}
}
?>
示例 3
<?php
class Dummy {
public function __get() {
/*
load stuff here because undefined
properties are caught by __get too
*/
}
}
?>
示例 3 关于结构的信息最少,但就内存而言,这是最好的方法。我们在谈论延迟加载的东西......即不将无用的东西加载到内存中,对吗?
我这样说是因为:
class x { protected $var1 = array(); protected $var2 = 0.0; }
比吃掉更多的内存
class x { protected $var1; protected $var2; }
甚至超过
class x { }
我通过构建数百万个对象并比较峰值内存使用情况对其进行了测试。