PHP:动态实例化类并从变量执行函数

时间:2013-12-08 21:12:17

标签: php

我正在尝试通过从某些变量中获取类名和方法名来动态实例化一个类并执行一个方法。

这是我正在使用的代码:

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

我一直收到以下错误:

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

我也尝试用经典的方式编写整个代码,它没有问题。

1 个答案:

答案 0 :(得分:1)

如果要使用类名变量创建类的实例,则必须确保类名是完全限定的(请参阅related section of the manual)。

在您的情况下,假设类API和要实例化的类是同一名称空间的成员,您可以使用__NAMESPACE__常量来构造完全限定名称:

$fqcn = __NAMESPACE__ .'\\'.$this->endpoint;
$endpointClass = new $fqcn;
相关问题