【问题标题】:Can't access property in abstract class via sub class无法通过子类访问抽象类中的属性
【发布时间】: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


【解决方案1】:

您正在尝试做的事情应该有效。确保您没有在UserController 中掩盖您的构造函数。 (即,如果它有构造函数,则需要调用其父构造函数。)

否则,请进行一些调试以查看 $this->view 被重置的位置。

【讨论】:

    【解决方案2】:

    您的代码对我有用。您要么覆盖 UserController 中的 __construct() 方法,要么使用 View 对象以外的其他对象覆盖 view 字段。

    您在此表单中的内容会起作用。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      • 2013-11-05
      • 2014-10-11
      相关资源
      最近更新 更多