DEV Community

jmau111⚡⚡⚡
jmau111⚡⚡⚡

Posted on

Why use PHP 8 constructor promotion?

If you're new to PHP, you start with a convenient syntax to write your classes.

Prior to PHP 8, developers used to write properties like that:

class Post
{
    public string $title;
    public string $id;

    public function __construct(
        string $title, 
        string $id
    ) {
        $this->title = $title;
        $this->id = $id;
    }
}
Enter fullscreen mode Exit fullscreen mode

If it seems redundant, that because it is, but the good news is that PHP 8 removes the hassle of repeating the same lines over and over.

The new syntax

class Post
{
    public function __construct(
        public string $title, 
        public string $id
    ) {}
}
Enter fullscreen mode Exit fullscreen mode

You can even add default values if you need it. It's also available in traits.

Behind the scene, PHP does the necessary assignments for you.

Using promoted properties

Just like before PHP 8:

// e.g., within the class
$this->title
$this->id

// with accessors outside if your properties are not public
Enter fullscreen mode Exit fullscreen mode

What about attributes and PHP doc?

Just like before, except that you will apply that on the constructor:

class Post
{
    public function __construct(
         #[CustomAttribute]
        public string $title, 
        public string $id
    ) {}
}
Enter fullscreen mode Exit fullscreen mode

When is it useful?

I would say "most of the time," but especially for value objects that contain lots of property declarations.

Of course, there are some subtleties to know for edge cases, but this syntax is pretty straighforward.

Read the full RFC here.

Top comments (0)