0

I have a function as:

public function controller_instance($controller_name)
{
      $controller = Router::getRequestedController();
      return $controller instanceof $controller_name;

}

and I call the function as controller_instance('IndexController').

This is always returning false because variable $controller_name contains string IndexController.

How can I make this work?

1
  • What does Router::getRequestedController() return? Commented Apr 14, 2016 at 10:12

2 Answers 2

2

Just make new class from that controller string

return $controller instanceof (new $controller_name());
Sign up to request clarification or add additional context in comments.

Comments

0

Are you expecting a instance or boolean?

Make a array property in the same class where contains the method controller_instance and store all instances

private $controllers = array();

public function controller_instance($controller_name)
{
    if (isset($this->controllers[$controller_name])) {
        return $this->controllers[$controller_name];
    }
    return $this->controllers[$controller_name] = new $controller_name();
}

Exemple 2: using ReflectionClass and arguments

private $controllers = array();

public function controller_instance($controller_name, Array $args = array())
{
    if (isset($this->controllers[$controller_name])) {
        return $this->controllers[$controller_name];
    }

    $class = new ReflectionClass($controller_name);

    $instance = $class->newInstanceArgs($args);

    return $this->controllers[$controller_name] = $instance;
}

Comments

Your Answer

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