PHP嵌套静态变量访问以进行依赖注入 [英] PHP Nested Static Variable Access for Dependency Injection

查看:122
本文介绍了PHP嵌套静态变量访问以进行依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用此模式在代码中启用依赖项注入。
我觉得它与动态语言的play-doh性质保持一致[1]。

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

推荐答案

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

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

这篇关于PHP嵌套静态变量访问以进行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆