Recall & Review
beginner
What is constructor promotion in PHP?
Constructor promotion is a feature introduced in PHP 8.0 that allows you to declare and initialize class properties directly in the constructor parameters, reducing boilerplate code.Click to reveal answer
beginner
How do you declare a promoted property in a PHP constructor?
You add visibility keywords (public, protected, private) before the constructor parameter. PHP automatically creates and initializes the property with the passed value.
Click to reveal answer
beginner
Example: What does this PHP code do?
<pre>class User {
public function __construct(private string $name) {}
}</pre>This code creates a class User with a private property $name. The property is declared and initialized directly via the constructor parameter using constructor promotion.Click to reveal answer
intermediate
Can constructor promotion be used with default parameter values?
Yes, you can assign default values to promoted parameters in the constructor, just like regular parameters.
Click to reveal answer
beginner
What are the benefits of using constructor promotion?
It reduces boilerplate code by combining property declaration and initialization in one place, making code shorter and easier to read.
Click to reveal answer
What keyword must you add before a constructor parameter to promote it to a property?
✗ Incorrect
You use visibility keywords like public, protected, or private before the parameter to promote it.
Which PHP version introduced constructor promotion?
✗ Incorrect
Constructor promotion was introduced in PHP 8.0.
What happens if you omit the visibility keyword in a constructor parameter?
✗ Incorrect
Without a visibility keyword, the parameter is not promoted and behaves like a normal constructor parameter.
Can constructor promotion be used with readonly properties?
✗ Incorrect
You can promote readonly properties by adding the readonly keyword after the visibility keyword.
Which of these is a valid promoted constructor parameter?
✗ Incorrect
Only parameters with visibility keywords like public string $name are promoted.
Explain constructor promotion in PHP and how it simplifies class property declaration and initialization.
Think about how you normally declare properties and assign them in the constructor.
You got /3 concepts.
Write a simple PHP class using constructor promotion to declare two properties: a public string $title and a private int $year.
Use public and private before the parameters in the constructor.
You got /4 concepts.