Constructor Property Promotion in PHP8

Constructor property promotion in PHP8 code example

Constructor property promotion in PHP8 is one of the new features which make our code less verbose and less error-prone. Similar to the match expressions which I wrote about last week.

Before we see what constructor property promotions in PHP8 look like, let’s take a look at a typical class declaration.

class Topic
{
	protected $name;

	function __construct($name)
	{
		$this->name = $name;
	}
}

class Tag
{
	protected $name;

	function __construct($name)
	{
		$this->name = $name;
	}
}

class Blog
{
	protected $title;
	protected Topic $topic;
	protected Tag $tag;

	function __construct($title, Topic $topic, Tag $tag)
	{
    $this->title = $title;
		$this->topic = $topic;
		$this->tag = $tag;
	}
}

As you can see, to declare a class like Topic with just one property name we have to write the same thing again and again. And when we repeat ourselves like that, we are increasing the chance of errors. For instance, we have referred to the name variable four times in the Topic class.

The same thing happens in the Tag class. We declare the name property, receive it as a parameter in our constructor and assign it to the current instance.

Finally, in the Blog class, we refer to both Topic and Tag classes as dependency injection. This is business as usual in OOP programming in PHP and most other programming languages.

The problem is, it is very verbose.

That is where constructor property promotions come in and save the day. In PHP8, we don’t have to do this repeated reference to the properties. Instead, we will promote them into our constructor and we are good to go. Here is an example:-

class Topic
{
	function __construct(protected $name){ }
}

class Tag
{
	function __construct(protected $name){ }
}

class Blog
{
	function __construct(protected $title, protected Topic $topic, protected Tag $tag){ }
}

In PHP8, we can specify the type and the access modifier of the property in the constructor itself. Then, PHP will understand what we are trying to accomplish.

Now our code is way smaller and much more readable once we understand what is happening.

To sum up, PHP introduces a number of new features in its new version 8 release. And one of them is constructor property promotion. Constructor property promotion in PHP8 encourages code readability and makes our code less error-prone.

Your subscription could not be saved. Please try again.
Your subscription has been successful.

Learn Modern JS, CSS, & PHP

Subscribe to learn modern PHP in the most simple way.