在PHP中挂钩变量调用

时间:2015-02-05 16:00:06

标签: php autoload magic-methods

我正在尝试存档的是一种自动加载器,用于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

有没有可以存档的钩子?

[编辑]: 用例是我正在尝试重构语言属性的加载。它们存储在文件中,因为它们总是被完全加载,即使它们未被使用,也会变得非常抽真空并且占用大量内存。

用函数调用交换所有变量是行不通的,因为在任何地方需要几个月来替换,特别是因为如果变量嵌入字符串中,搜索和替换将不起作用。

另一个重构是将变量移动到数据库,这可以在脚本中完成。但是一次加载所有变量的加载过程在运行时会非常困难。

1 个答案:

答案 0 :(得分:1)

如果你知道它的结构,有可能使$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'];

这种方法可以做到的一切都是一种练习。