Create promoted properties in PHP 8 classes
Since this convention is so common in code, PHP 8 introduced a shorthand for this process. Rather than creating a class property with a scope keyword, assigning it the name within a method argument, and assigning the value back to the property with $this
, we can use a shorthand syntax. This is called “promoted properties”, or “constructor property promotion”, and greatly simplifies your code. It also eliminates a lot of the repeition happening with the naming of these properties and values. You can see that this $name
name is referred to 4 times in the code.
Rather than defining the scope & casting of the class property at the top of the class, we will move it to directly before the related method argument.
<?php declare(strict_types=1); class Author { public function __construct(public string $name) { $this->name = $name; } }
You can see that PHPStorm grayed out the property assignment within the constructor. This is because PHP 8 has already assigned it to the class property! So we can remove this dead code. By simply defining the method argument with a scope keyword, it also assigns it to a class property with the same name. This eliminates all of the duplication of the class property name within our code.
<?php declare(strict_types=1); class Author { public function __construct(public string $name) { } }
Because there can be many arguments defined within a constructor, it’s common practice to break each of these method arguments onto their own line. This makes code much more readable and easier to understand.
<?php declare(strict_types=1); class Author { public function __construct( public string $name ) {} }
It’s also a good idea to move the closing parenthesis and brackets all onto a single line, to save some line break space since this method body is empty.
This code is exactly equivalent to the previous $this
assignment of class properties in the previous lesson.