1. 41
    Create promoted properties in PHP 8 classes
    2m 12s

Create promoted properties in PHP 8 classes

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

There's a new way to create class properties in PHP 8. In this lesson, you'll learn about "promoted properties", also referred to as "constructor property promotion".

Mark Shust: [0:00] Since this convention of creating a class property up here, passing in an argument name, and then assigning that argument to the property is so common in code, PHP 8 introduced a shorthand for this process. [0:15] This shorthand is a new feature of PHP 8 called promoted properties, or Constructor Property Promotion, and it greatly simplifies your code. It also eliminates a lot of the repetition happening with the naming of these properties and values.

[0:30] You'll notice that this name is referenced four times throughout our code. Constructor Property Promotion replaces this with a single reference. Rather than defining the scope and casting of the class property at the top of the class, we will move it to directly within our related argument.

[0:50] Rather than having public string up here, let's go ahead and move it to before our argument name. By doing this, we can eliminate this class property definition at the top of the file.

[1:03] You will also notice that PhpStorm grayed out this, this name assignment within the constructor. This is because PHP 8 has already assigned it to the class property by defining the scope within our argument definition. We can remove this dead code.

[1:22] By simply defining the method argument with a scope, it assigns it to a class property with the same name. This eliminates all of the duplication of the class property name within our code.

[1:35] Because there can be many arguments to find within a constructor, it's common practice to break each of these method arguments on to their own line. This makes code much more readable and easier to understand.

[1:50] It's also a good idea to move the closing parentheses and brackets all to their own line. This will save a lot of space with line breaks, especially since this method body is now empty. This code is the exact equivalent of the previous this assignment of class properties in the previous lesson.