PHP:通过字符串值获取静态类的实例 [英] PHP: Get instance of static class by string value
问题描述
我正在开发一个PHP Web API,该Web API已交付给我,其中包含许多需要重构的代码.编写该代码的人希望将静态配置类包含到api资源中,然后获取该类的实例,如下所示:
I'm working on a php web api that was handed to me with a lot of code that needs to be refactored. The ones that wrote the code wanted to include a static configuration class to an api resource and then get an instance of that class something like this:
<?php
$obj = "User";
$confObjectSuffix = "_conf";
$confObject = $obj.$confObjectSuffix;
if ($confObject::inst()->checkMethod($method)) {
.....
由于$ confObject是字符串而不是对象,因此出现错误解析错误:语法错误,在.....中出现意外的T_PAAMAYIM_NEKUDOTAYYIM".
This gives the error "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ....." since $confObject is a string and not a object.
我写了一些测试代码:
<?php
$class = "User_conf";
echo "<pre>";
print_r($$class::Inst());
echo "</pre>";
class User_conf {
private static $INSTANCE = null;
public static function Inst() {
if(User_conf::$INSTANCE === null) {
User_conf::$INSTANCE = new User_conf();
}
return User_conf::$INSTANCE;
}
}
但是也不能使其与$$一起使用,是否还有其他解决方法?我不想重写过多的内容.
But can't get it to work with $$ either, is there some other way around this? I don't want to rewrite more than necessary.
推荐答案
您可以使用call_user_func
捕获实例,然后根据需要对其进行处理:
You can use call_user_func
to capture the instance, then process it as needed:
$instance = call_user_func(array($confObject, 'inst'));
if($instance->checkMethod($method)) {
...
这篇关于PHP:通过字符串值获取静态类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!