Constructor promotion got introduced in PHP 8.
This is how we used constructor with arguments before PHP 8
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
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.
class constructor examples object-oriented OOP update