PHP嵌套静态变量访问依赖注入


PHP Nested Static Variable Access for Dependency Injection

我想使用这种模式在我的代码中启用依赖注入。我觉得它与动态语言的橡皮泥特性保持一致[1]。

class A {
  static $FOO = 'Foo';
  function __construct() {
    $this->foo = self::$FOO::getInstance();
  }
}
A::$FOO = 'MockFoo';
$a = new A();

不幸的是,这不起作用,我得到:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in [test.php] on line 6
我可以创建一个临时变量来欺骗解析器,但是还有其他方法吗?
function __construct() {
  $FOO = self::$FOO;                                                                                                                                            
  $this->foo = $FOO::getInstance();
}

[1] http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming

没有其他语法可以完成此操作。需要一个临时变量来欺骗解析器。

Try

$class = self::$FOO;
$this->foo = $class::getInstance();