我正在为一个基本的MVC练习,但是我收到了这个错误:
Fatal error: Call to a member function run() on a non-object in Router.php on line 5
我做错了什么?
核心:
<?php
class Core {
protected $router;
protected $controller;
public function run() {
$this->router =& load_class('Router');
$this->controller =& load_class('Controller');
$this->router->run();
}
}
路由器:
class Router extends Core {
public function run() {
echo $this->controller->run();
}
}
控制器:
class Controller extends Core {
public function run() {
return 'controller';
}
}
哦,还有load_class函数
function &load_class($class_name) {
$path = ROOT . 'system/classes/' . $class_name . '.php';
if (file_exists($path)) {
include_once($path);
if (class_exists($class_name)) {
$instance = new $class_name;
return $instance;
}
}
return false;
}
非常感谢。
答案 0 :(得分:2)
如果扩展扩展以查看其实际外观,您将看到它失败的原因:
class Core {
protected $router;
protected $controller;
public function run() {
$this->router =& load_class('Router');
$this->controller =& load_class('Controller');
$this->router->run();
}
}
参加:
class Router extends Core {
public function run() {
echo $this->controller->run();
}
}
大致与:
相同class Router {
protected $router;
protected $controller; // <- this is "$this->controller"
public function run() {
echo $this->controller->run();
}
}
你可以看到$ this-&gt; controller是一个变量,所以没有方法
因此,在扩展版本中,您需要使用parent :: $ controller-&gt; run();
引用父类。答案 1 :(得分:0)
我可能会离开这里,但是通过在每个类中扩展Core
,我认为你无意中重写了run()
方法并且混淆了每个类的范围。您是否尝试过从单独的非扩展类中调用run()
?