mhvvzmak1
mhvvzmak1

Reputation: 317

PHP - How to extend and access parent constructor properties

I am attempting to access the parent class __construct properties within a child class that extends this, however not sure how to do this as I have tried multiple methods and didn't give me the expected result.

So I have a baseController and a indexController which extends it, I want to be able to have direct access to the properties of the parent within the child controller.

$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

Upvotes: 0

Views: 5820

Answers (1)

KDaker
KDaker

Reputation: 5909

There are several issues with code you have there. You are setting up config as a global, it should be inside your BaseController and set it to public or protected:

class BaseController {
  protected $config = ...

Just like @mhvvzmak1 mentioned, your child constructor is calling the parent properly. for example you can do it like so:

 class IndexController extends BaseController {

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

and finally just like dan08 mentioned, you can't reference $this from a static method, change your index function:

public function index() {

Update

If you really want the child function to remain static as required by your framework, you make config a static function on the BaseController and call it in the child.

class BaseController {

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

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

Upvotes: 0

Related Questions