Yogesh Chauhan's Blog

What’s new in Constructor in PHP 8?

in PHP on June 14, 2021

Constructor promotion got introduced in PHP 8.

This is how we used constructor with arguments before PHP 8


<?php
class Point {
    protected int $x;
    protected int $y;

    public function __construct(int $x, int $y = 0) {
        $this->x = $x;
        $this->y = $y;
    }
}
?>


If a class doesn’t have a constructor or if the arguments are not required then you can omit the parentheses.

Before PHP 8, there were old-style constructors. Meaning you can define a method named after the class and the classes in the global namespace will interpret it as a constructor. That is deprecated now.

As of PHP 8, if you define a __construct() and a method names after class then __construct() will be called.

Always use __construct() in new code.


Constructor Promotion

From PHP 8, you can add constructor parameters to correspond to an object property.

Conventionally we assign constructor parameters to a property inside the constructor but they are not used. But constructor promotion gives you a quick and easy way to do both.

This is how we can write a class with a constructor promotion in PHP


<?php
class Point {
    public function __construct(protected int $x, protected int $y = 0) {
        $this->x = $x;
        $this->y = $y;
    }
}
?>


PHP will interpret the whole package (a constructor argument with a visibility modifier) as an object property and a constructor argument. PHP assigns the argument value to the property.

You may have the constructor body completely empty too! If you want, you can add statements inside the constructor body. The statements you add inside the constructor body will be executed after PHP assigns the argument values to the properties.

You are not required to promote all arguments. It’s completely up to you. You can mix and match arguments in any order.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a Recent Posts function in WordPress?WordPressWhat are components in Angular?AngularUnderstand Inheritance in PHP in this Basic Example (For Beginners)PHPSelect statement in Postgres with examplesPostgresMoving folders in WordPress using codeWordPressHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScript