Video Lesson: Create promoted properties in PHP 8 classes

Create promoted properties in PHP 8 classes

Learn how to use constructor property promotion to define and initialize class properties more concisely.


Lesson Content

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 string $name;

    public function __construct($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.

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.

Code Diff

diff --git a/classes/Author.php b/classes/Author.php
index 67181da..f40e6fe 100644
--- a/classes/Author.php
+++ b/classes/Author.php
@@ -2,10 +2,7 @@
 
 class Author
 {
-    public string $name;
-
-    public function __construct($name)
-    {
-        $this->name = $name;
-    }
+    public function __construct(
+        public string $name
+    ) {}
 }
Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!