0

我正在尝试访问扩展它的子类中的父类 __construct 属性,但是不确定如何执行此操作,因为我尝试了多种方法并且没有给我预期的结果。

所以我有一个 baseController 和一个扩展它的 indexController,我希望能够直接访问子控制器中父级的属性。

            $config = ['site' => 'test.com'];

            class baseController {

                public function __construct($config){

                    $this->config = $config;

                }

            }

            class indexController extends baseController {

                public function __construct(){
                    parent::__construct(); // doesnt seem to give any outcome
                }

                public static function index() {

                    var_dump($this->config); // need to access within this method

                }

            }

            $app->route('/',array('indexController','index')); // the route / would call this controller and method to return a response
4

1 回答 1

0

您那里的代码有几个问题。您正在将 config 设置为全局,它应该在您的内部BaseController并将其设置为publicor protected

class BaseController {
  protected $config = ...

就像提到的@mhvvzmak1 一样,您的子构造函数正在正确调用父级。例如你可以这样做:

 class IndexController extends BaseController {

     public function __construct(){
         $config = [];
         parent::__construct($config);
     }

最后就像提到的 dan08 一样,你不能$this从静态方法中引用,改变你的索引函数:

public function index() {

更新

如果您真的希望子函数按照框架的要求保持静态,您可以在 config 上设置一个静态函数并在子函数BaseController中调用它。

class BaseController {

   protected static function config() {
     return ['site' => 'mySite'];
   }
}

class Child extends BaseController {
   public static function index() {
      $config = BaseController::config();
   }
}
于 2016-04-05T22:01:54.653 回答