Using Constructor Property Promotion

Learn how constructor property promotion significantly reduces the lines of code.

Aside from the Just-In-Time (JIT) compiler, one of the greatest new features introduced in PHP 8 is constructor property promotion. This new feature combines property declarations and argument lists in the __construct() method signature, as well as assigning defaults. In this section, we will learn how to substantially reduce the amount of coding required in property declarations as well as in the __construct() method signature and body.

Property promotion syntax

The syntax needed to invoke constructor property promotion is identical to that used in PHP 7 and earlier, with the following differences:

  • We need to define a visibility level.

  • We do not have to declare the properties in advance explicitly.

  • We do not need to make assignments in the body of the __construct() method.

Here is a bare-bones example of code that uses constructor property promotion:

Get hands-on with 1200+ tech skills courses.