繁体   English   中英

PHP-如何扩展和访问父构造函数属性

[英]PHP - How to extend and access parent constructor properties

我正在尝试访问子类中的父类__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

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

class BaseController {
  protected $config = ...

就像提到的@ mhvvzmak1一样,您的子构造方法会正确调用父方法。 例如,您可以这样做:

 class IndexController extends BaseController {

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

最后就像dan08提到的那样,您不能从静态方法中引用$this ,而是要更改索引函数:

public function index() {

更新资料

如果您确实希望子功能按照框架的要求保持静态,则可以在BaseController config BaseController静态功能,然后在BaseController调用它。

class BaseController {

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

class Child extends BaseController {
   public static function index() {
      $config = BaseController::config();
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM