PHP ยท Chapter 36 of 44

PHP Constructors

A constructor is a special method automatically called when a new object is created from a class. In PHP, the constructor method is named __construct(), and it is typically used to set up initial values for an object's properties.

Constructors can accept parameters just like regular functions, allowing you to pass in initial data when creating an object, which avoids having to set each property manually afterward.

Syntax
class MyClass {
  function __construct($value) {
    $this->property = $value;
  }
}

Defining a constructor

__construct() is defined inside a class like any other method, but PHP calls it automatically whenever new ClassName() is used.

Constructor property promotion

Since PHP 8, you can declare and assign properties directly in the constructor's parameter list, reducing boilerplate code.

Example 1 (php)
<?php
  class Person {
    public $name;
    function __construct($name) {
      $this->name = $name;
    }
  }
  $p = new Person("Amy");
  echo $p->name;
?>
Output
Amy

The constructor sets the name property automatically when the object is created.

Example 2 (php)
<?php
  class Point {
    public function __construct(public $x, public $y) { }
  }
  $p = new Point(3, 4);
  echo "$p->x, $p->y";
?>
Output
3, 4

Constructor property promotion declares and assigns $x and $y in a single step.

Key points

  • __construct() runs automatically when an object is created.
  • Constructors often initialize an object's properties.
  • Constructors can accept parameters like regular functions.
  • Constructor property promotion (PHP 8+) shortens property setup code.
๐Ÿ’ก Note: If a class has no constructor defined, PHP simply skips this step and properties keep their default values.

๐Ÿ“ Quick Quiz

1. What is the name of PHP's constructor method?

2. When does the constructor run?

3. What does constructor property promotion do?