我试图归档的是php中变量的自动加载器。有什么方法可以挂接php中的变量加载吗?
示例用法为:
function __autoloadVar($varname,$indices){
global $$varname;
if(count($indices) > 0 && !isset($$varname[$indices[0]])){ //first index
$$varname[$indices[0]] = load_var_content($indices[0]); //this would call a function that loads a variable from the database, or another source
}
}
echo $foo["bar"]["baz"];
// => calls __autoloadVar("foo",array("bar","baz")) then accessing it
有什么可以存档的钩子吗?
[编辑]:用例是我正在尝试重构语言属性的加载。它们存储在文件中,这些文件已经变得非常密集和内存密集,因为它们总是完全加载的,即使它们是未使用的。
用函数调用交换所有变量是不起作用的,因为这需要几个月的时间来替换所有变量,尤其是因为如果变量嵌入字符串中,搜索和替换就不起作用。
另一个重新实现是将变量移动到数据库中,这可以在脚本中完成。但是一次加载所有变量的加载过程在运行时会受到太大的冲击。
如果你知道$foo
的结构,就有可能让它变得有点"神奇":
class Foo implements ArrayAccess {
private $bar;
public function offsetGet($name) {
switch($name) {
case "bar":
if(empty($this->bar)) $this->bar = new FooBar;
return $this->bar;
}
}
public function offsetExists($offset) { }
public function offsetSet($offset, $value) { }
public function offsetUnset($offset) { }
}
class FooBar implements ArrayAccess {
private $baz;
public function offsetGet($name) {
switch($name) {
case "baz":
if(empty($this->baz)) $this->baz = new FooBarBaz;
return $this->baz;
}
}
public function offsetExists($offset) { }
public function offsetSet($offset, $value) { }
public function offsetUnset($offset) { }
}
class FooBarBaz {
public function __toString() {
return "I'm FooBarBaz'n";
}
}
$foo = new Foo;
echo $foo['bar']['baz'];
这种方法所能做的一切都只是一种练习。