PHP OOP - Parent constructors

Last revision:

Overview

Constructors are special class methods that are automatically called when objects are created. They typically initialize the object by providing initial values to some of the object's properties.

Constructors play an important role in inheritance as well, so you need to know how to work with parent constructors and child constructors.

Child class without own constructor

If a child class does not have its own constructor, its parent's constructor, if present, is automatically called when an object of the child class is constructed.

As a result, if the parent constructor requires parameters, you will have to provide those when instantiating the child class:

Code
<?php

class Animal {
  
  public int $num_legs;

  public function __construct(int $num_legs) {
    $this->num_legs = $num_legs;
  }

}

Class dog extends Animal {

  public string $name;
  
  public function bark(): void {
    print("{$this->name} is barking: woof!");
  }

}

$mydog = new Dog(4);
$mydog->name = 'Rufus';
$mydog->bark();

In this example you'll get an error when trying to construct a new Dog object without passing a parameter. The Dog class doesn't have a constructor, so the parent constructor is called, and that one requires a parameter.

Child class with own constructor

If a child class has its own constructor, that constructor is called when the class is instantiated, and the parent constructor, if it exists, will no longer be called automatically.

If your child class defines a constructor and you also want the parent constructor to be called, you'll have to call it yourself using parent::__construct(), passing along all necessary parameters:

Code
<?php

class animal {
 
 public int $num_legs;

 public function __construct(int $num_legs) {
   $this->num_legs = $num_legs;
 }

}

class Dog extends Animal {

 public string $name;

 public function __construct($name, $num_legs) {
   $this->name = $name;
   parent::__construct($num_legs);
 }
 
 public function bark(): void {
   print("{$this->name} is barking: woof!");
 }

}

$mydog = new Dog('Rufus', 4);

Summary

  • If a child class does not define a constructor, the parent constructor is called.
  • If a child class does define its own constructor, that constructor is called during instantiation, and the parent constructor is not.
  • A child constructor can call its parent's constructor using parent::__construct().