简体   繁体   中英

PHP: Dynamically instantiate class and execute function from variables

I'm trying to dynamically instantiate a class and executing a method by getting the class name and the method name from some variables.

This is the code i'm using:

public function processAPI() {

    // Require the PHP file that containes the class
    require_once(Settings\Path\Absolute::$engine."/class".$this->endpoint.".php");

    // $this->endpoint is a string containing the class name (this is where i get the error, line 128)
    $endpointClass = new $this->endpoint;

    // $this->verb is the method (function) name
    if(method_exists($endpointClass, $this->verb) > 0) {

        // Executes the class method and returns it. $this->args is an array containing the arguments.
        return $this->response(call_user_func_array($endpointClass->{$this->verb}, $this->args));
    }

    return $this->response('', 400);
}

I keep receiving the following error:

Fatal error: Class 'User' not found in D:\...\webname\resources\engine\classAPI.php on line 128

I also tried writing the whole code in the classic way and it's working without problems.

When you want to create an instance of a class using a variable for the class name you must make sure that the class name is fully qualified (see related section of the manual ).

In your case, assuming that class API and the class you want to instantiate are members of the same namespace, you can use the __NAMESPACE__ constant to construct a fully qualified name:

$fqcn = __NAMESPACE__ .'\\'.$this->endpoint;
$endpointClass = new $fqcn;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM