我正在做一个基本的 MVC 练习,但我得到了这个错误:
fatal error :第 5 行在 Router.php 中的非对象上调用成员函数 run()
我做错了什么?
核心:
<?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();
}
}
Controller :
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;
}
提前致谢。
最佳答案
如果您展开扩展以查看它的实际外观,您就会明白它失败的原因:
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->controller 是一个变量所以没有方法
因此在扩展版本中,您需要使用 parent::$controller->run(); 来引用父类
关于php - 访问兄弟类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304923/