问题
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