Can't call static method from class as variable name?

巧了我就是萌 提交于 2019-12-01 04:51:43

Yes. That syntax was introduced in 5.3

To workaround for <= 5.2, you can use call_user_func:

call_user_func(array($className, $funcName), $arg1, $arg2, $arg3);

or call_user_func_array:

call_user_func_array(array($className, $funcName), array($arg1, $arg2, $arg3));

But on another note, what you're trying to do doesn't really make sense...

Why have it as a static function? Your constructor in implementation is expecting an object anyway (that's what strategyInterface $strategy is looking for). Passing a string won't work, since strings don't implement interfaces. So what I would do, is make the interface non-static, and then do something like:

$strategy = new StrategyB();
$implementation = new Implementation($strategy);

Then, in the constructor:

$strFormat = $strategy->getFormatString();

Or, if you really still want that method to be static you could do:

$strFormat = call_user_func(array(get_class($strategy), 'getFormatString'));

Oh, and = & new synax is deprecated (and doesn't do what you think it does anyway).

Type hinting is going to give you some problems:

Argument 1 passed to implementation::__construct() must implement interface strategyInterface, string given

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