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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Dec 4 What is Etrieve Flow? #Dec 2 The unique operator($) in Envision Basic #Nov 25 Steps to Install Microsoft SQL Server on a MacOS #Nov 11 What is DevOps? #Nov 10 The * arithmetic operator in Envision Basic #Nov 10 What are Big Data Clusters in SQL Server?
You might also like these
What is an API?MiscellaneousImplicit and Explicit Joins in Oracle SQLSQL/MySQLRIGHT JOIN in PostgresPostgresHow to add Read More Read Less Button using JavaScript?JavaScriptHow to uninstall Cocoapods from the Mac OS?MiscellaneousHow to get user’s Browser and Operating Systems information using PHP?PHP