【发布时间】:2012-04-28 17:19:17
【问题描述】:
我正在尝试构建一个抽象的基本控制器,它将扩展所有其他控制器。到目前为止,我有类似的东西:
abstract class BaseController {
protected $view;
protected $user;
public function __construct() {
$this->view = new View; //So a view is accessible to subclasses via $this->view->set();
$this->user = new User; //So I can check $this->user->hasPermission('is_admin');
}
abstract function index();
}
class UserController extends BaseController {
public function index() {}
public function login() {
if($this->user->isLoggedin()) {
redirect to my account
}
else {
$this->view->set('page_title', "User Login");
$this->view->set('sidebar', $sidebar); //contains sidebar HTML
$this->view->set('content', $content); //build main page HTML
$this->view->render();
}
}
}
我遇到的问题是这样的错误:
Call to a member function set() on a non-object in C:\xampp\htdocs\program\core\controllers\admin.controller.php on line 44
如果我将 $user 和 $views 属性放在主控制器(即 UserController)中,一切正常。但我只想设置这些对象一次(在基本控制器中),而不必在我的所有控制器中添加$this->view = new View;。
已修复: 我覆盖了我的构造函数,我认为你不能在抽象类上调用 parent::__construct()。
【问题讨论】:
-
您是否以我们在这里看不到的方式覆盖了构造函数,如果是,您是否调用了 parent::__construct()?
-
您的代码适用于我的测试用例。您已经覆盖了 __constructor。
标签: php model-view-controller inheritance abstract-class