簡體   English   中英

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

沒有其他語法可以完成此操作。 您需要一個臨時變量來欺騙解析器。

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM