0

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.

10
  • Perhaps class User is inside a namespace and $this->endpoint is not a fully qualified name? Keep in mind that if you have imported a class User with use then you can straight-instantiate it with new User but you cannot do the same with new $class if $class is not fully qualified. Commented Dec 8, 2013 at 21:14
  • ` > 0)` what is the point of that? Commented Dec 8, 2013 at 21:17
  • @Jon The classAPI.php and classUser.php are both in the same namespace. Commented Dec 8, 2013 at 21:19
  • @ShadowBroker: So that's the problem right there. It doesn't matter if they are in the same namespace, you still have to fully qualify the name if it's in a variable. Try __NAMESPACE__.'\'.$this->endpoint as the class to instantiate and see. Commented Dec 8, 2013 at 21:19
  • @RPM That simply means true i can change it to == true. Commented Dec 8, 2013 at 21:20

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.