我的功能如下:
public function controller_instance($controller_name)
{
$controller = Router::getRequestedController();
return $controller instanceof $controller_name;
}
我将该函数称为controller_instance('IndexController')
。
这总是返回false,因为变量$controller_name
包含字符串IndexController
。
我该如何做到这一点?
答案 0 :(得分:2)
只需从该控制器字符串中创建新类
return $controller instanceof (new $controller_name());
答案 1 :(得分:0)
您是期待实例还是布尔值?
在包含方法 controller_instance 的同一个类中创建一个数组属性并存储所有实例
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();
}
例2:使用ReflectionClass和参数
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;
}