PHP Classes and Objects Calling a parent constructor when instantiating a child

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A common pitfall of child classes is that, if your parent and child both contain a constructor(__construct()) method, only the child class constructor will run. There may be occasions where you need to run the parent __construct() method from it's child. If you need to do that, then you will need to use the parent:: scope resolutor:

parent::__construct();

Now harnessing that within a real-world situation would look something like:

class Foo {

    function __construct($args) { 
        echo 'parent'; 
    }

}

class Bar extends Foo {

    function __construct($args) {
        parent::__construct($args);
    }
}

The above will run the parent __construct() resulting in the echo being run.



Got any PHP Question?