开发者

PHP: Get instance of static class by string value

开发者 https://www.devze.com 2022-12-23 22:53 出处:网络
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 t

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)) {
.....

This gives the error "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ....." since $confObject is a string and not a object.

I wrote some testcode:

<?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();
        }

开发者_StackOverflow社区        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.


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)) {
    ...
0

精彩评论

暂无评论...
验证码 换一张
取 消