我正在尝试构建一个抽象的基本控制器,它将扩展所有其他控制器。到目前为止,我有类似的东西:
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()。