PHP Nested Static Variable Access for Dependency Injection

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 10:24:02

问题


I would like to use this pattern to enable dependency injection in my code. I feel that it keeps with the play-doh nature of dynamic languages [1].

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

A::$FOO = 'MockFoo';
$a = new A();

Unfortunately, this doesn't work and I get:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in [test.php] on line 6

I can create a temporary variable to trick the parser, but is there another way?

function __construct() {
  $FOO = self::$FOO;                                                                                                                                            
  $this->foo = $FOO::getInstance();
}

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


回答1:


There is no alternative syntax to accomplish this. You need a temporary variable to trick the parser.




回答2:


Try

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


来源:https://stackoverflow.com/questions/7573166/php-nested-static-variable-access-for-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!