訪問抽象類中的屬性我想構建一個將擴展所有其他控制器的抽象基本控制器。到目前爲止,我有這樣的:不能通過子類
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
如果我把$用戶,並在主控制器$視圖屬性(即UserController中) ,一切正常。但我只想設置這些對象一次(在基本控制器中),而不必在我的所有控制器中添加$this->view = new View;
。
修復:我覆蓋了我的構造函數,我以爲你不能在抽象類上調用parent :: __ construct()。
您是否以我們在這裏沒有看到的方式重寫構造函數,如果是的話,您調用了parent :: __ construct()? – 2012-04-28 17:21:49
你的代碼適用於我的測試用例。您已覆蓋__constructor。 – 2012-04-28 17:27:19