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

您的代码有几个问题。您将配置设置为全局配置,它应该在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设置为静态函数,并在子函数中调用它。

class BaseController {
   protected static function config() {
     return ['site' => 'mySite'];
   }
}
class Child extends BaseController {
   public static function index() {
      $config = BaseController::config();
   }
}