Categories
PHP

PHP: Constructor Property Promotion

Constructor Property Promotion is a feature that was introduced in PHP 8.0 to reduce the amount of boilerplate code needed when defining class properties and a constructor that sets them. Before this feature, you had to do something like this:

class Example {
    private string $property;

    public function __construct(string $property) {
        $this->property = $property;
    }
}

With Constructor Property Promotion, you can simplify the above code like this:

class Example {
    public function __construct(private string $property) {}
}

Here’s a breakdown of how Constructor Property Promotion works:

  1. Type: You can declare the type of the property (like string, int, etc.).
  2. Visibility: You can specify the visibility of the property (public, protected, or private).
  3. Property: The property name is specified after the type and visibility.

In the simplified syntax, the parameter is promoted to be a property of the class, and the constructor automatically sets the property when the object is instantiated, which reduces redundancy in the code. This feature is particularly useful for value objects and data transfer objects, where classes often contain properties and simple constructors to set them.

A more extensive example with multiple properties might look like this:

class Point {
    public function __construct(
        private float $x = 0.0,
        private float $y = 0.0,
        private float $z = 0.0,
    ) {}

    // Additional methods here...
}

Note that you can use default values for the properties, just like you can with traditional constructor parameters. This simplifies the declaration and initialization of class properties, making the code more concise and potentially easier to read.

Leave a Reply

Your email address will not be published. Required fields are marked *