在 PHP 中挂钩变量调用

Hook variable call in PHP

我要存档的是 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 有点 "magical" 是可能的:

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'];

这种方法的所有可能性留作练习。