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 <span class="hljs-keyword">string</span> $<span class="hljs-keyword">property</span>;

    public function __construct(<span class="hljs-keyword">string</span> $<span class="hljs-keyword">property</span>) {
        $this-><span class="hljs-keyword">property</span> = $<span class="hljs-keyword">property</span>;
    }
}

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

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> {</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(</span><span class="hljs-keyword">private</span> string $<span class="hljs-keyword">property</span>) {}
}

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:

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> function <span class="hljs-title">__construct</span><span class="hljs-params">(
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">float</span> $x = <span class="hljs-number">0.0</span>,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">float</span> $y = <span class="hljs-number">0.0</span>,
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">float</span> $z = <span class="hljs-number">0.0</span>,
    )</span> </span>{}

    <span class="hljs-comment">// Additional methods here...</span>
}

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 *