Constructors in PHP

A special kind of method named __construct() is called constructor.

class Dog {
	public function __construct() {

  }
}

This method is used to initialize the properties of an object when you create it, as it’s automatically invoked when calling new Classname()

class Dog {
  public $name;

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

  public function bark() {
    echo $this->name . ' barked!';
  }
}

$roger = new Dog('Roger');
$roger->bark();

This is such a common thing that PHP (starting in PHP 8) includes something called constructor promotion where it automatically does this thing:

class Dog {
  public $name;

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

  //...

by using the access modifier, the assignment from the parameter of the constructor to the local variable is done automatically:

class Dog {
	public function __construct(public $name) {
  }

  public function bark() {
    echo $this->name . ' barked!';
  }
}

$roger = new Dog('Roger');
$roger->name; //'Roger'
$roger->bark(); //'Roger barked!'

Properties can be typed.

You can require the name to be a string using public string $name:

class Dog {
  public string $name;

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

  public function bark() {
    echo $this->name . ' barked!';
  }
}

$roger = new Dog('Roger');
$roger->name; //'Roger'
$roger->bark(); //'Roger barked!'

Now all works fine in this example, but try changing that to public int $name to require it to be an integer.

PHP will raise an error if you initialize $name with a string:

TypeError: Dog::__construct():
Argument #1 ($name) must be of type int,
string given on line 14

Interesting, right?

We can enforce properties to have a specific type between string, int, float, string, object, array, bool and others.

Download my free PHP Handbook!