Constructor Property Promotion in PHP 8
September 15, 2021
PHP 8 now offers us a way to simplify our class from three sets of data to one.
Originally, to instantiate a class with 3 properties (such as first name, last name and email), we would have a total of 3 sets of references to the properties in our class:
- We would declare the properties at the start of our class,
- we would provide arguments in the constructor function for values we'll use to populate our class properties, and
- we would assign the specific argument value to the associated property
class User
{
private $first_name;
private $last_name;
private $email;
public function __construct(string $first_name = '', string $last_name = '', string $email = '')
{
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->email = $email;
}
}
That's a lot of redundant typing!
With PHP 8's constructor property promotion we can now reduce the three separate sets into one set, used within the argument list of the constructor. This allows us to combine the need to declare the properties, identify values, and assign those values into one simple step.
How is that done? Easy, we simply specify the visibility, type and value of each property in the argument list of the constructor function as follows:
class User
{
public function __construct(
private string $first_name = '',
private string $last_name = '',
private string $email = ''
) {}
public function getUser()
{
return $this->first_name . ' ' . $this->last_name . ' (' . $this->email . ')';
}
}
The code is still clean, but now has a smaller footprint. Thanks PHP 8 :)