0
0
PHPprogramming~5 mins

Constructor inheritance in PHP

Choose your learning style9 modes available
Introduction

Constructor inheritance lets a child class use the setup steps from its parent class automatically. This saves time and avoids repeating code.

When a child class needs to start with the same setup as its parent class.
When you want to add extra setup steps in the child class but keep the parent's setup too.
When you want to organize code so common setup is in one place (the parent).
Syntax
PHP
<?php
class ParentClass {
    public function __construct() {
        // parent setup code
    }
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct(); // call parent's constructor
        // child setup code
    }
}
?>
Use parent::__construct(); inside the child's constructor to run the parent's constructor.
If you don't define a constructor in the child, PHP automatically uses the parent's constructor.
Examples
The child class Dog does not have its own constructor, so it uses the parent's constructor automatically.
PHP
<?php
class Animal {
    public function __construct() {
        echo "Animal created\n";
    }
}

class Dog extends Animal {
    // No constructor here
}

$dog = new Dog();
The child class Dog has its own constructor but calls the parent's constructor first using parent::__construct();.
PHP
<?php
class Animal {
    public function __construct() {
        echo "Animal created\n";
    }
}

class Dog extends Animal {
    public function __construct() {
        parent::__construct();
        echo "Dog created\n";
    }
}

$dog = new Dog();
Sample Program

This program shows a Vehicle class with a constructor that prints a message. The Car class extends Vehicle and calls the parent's constructor before printing its own message.

PHP
<?php
class Vehicle {
    public function __construct() {
        echo "Vehicle ready\n";
    }
}

class Car extends Vehicle {
    public function __construct() {
        parent::__construct();
        echo "Car ready\n";
    }
}

$myCar = new Car();
OutputSuccess
Important Notes

If the child class does not call parent::__construct();, the parent's constructor will not run.

Constructor inheritance helps keep code clean and avoids repeating setup steps.

Summary

Constructor inheritance lets child classes reuse parent setup code.

Use parent::__construct(); inside child's constructor to run parent's constructor.

If child has no constructor, parent's constructor runs automatically.