如何在 PHP 中引用变量类的静态方法?
我正在编写一个工厂类,它应该能够返回多种不同类型的单例实例,具体取决于给定的参数。该方法看起来像这样,但我引用单例静态方法的方式显然是错误的:
public function getService($singletonClassName) {
return $singletonClassName::getInstance();
}
这种引用的正确语法在 PHP 中是什么样子?
I'm writing a factory class that should be able to return singleton instances of a number of different types, depending on the given parameter. The method would look something like this, but the way I'm referencing the singleton's static method is obviously wrong:
public function getService($singletonClassName) {
return $singletonClassName::getInstance();
}
What would the correct syntax for such a reference look like in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能在 PHP < 中使用这种语法。 5.3 :它是 PHP 5.3 的新功能之一
,对于 PHP 5.2,有几种可能性是:
call_user_func
In the first case, it would be as simple as :
并且,在第二个中,您将使用类似以下内容的内容:
根据
call_user_func
,这应该适用于 PHP >= 5.2.3或者你可以只使用:
You cannot use that kind of syntax with PHP < 5.3 : it's one of the new features of PHP 5.3
A couple of possibilities, with PHP 5.2, would be to :
call_user_func
In the first case, it would be as simple as :
And, in the second, you'd use something like :
According to the documentation of
call_user_func
, this should work with PHP >= 5.2.3Or you could just use :
您只需使用类名
或者,如果
$singleClassName
是包含类名的变量,则使用从 5.2.3 开始,您也可以这样做
You just use the class name
Alternatively, if
$singleClassName
is a variable containing the classname useAs of 5.2.3 you can also do