0
0
PHPprogramming~5 mins

Constructor promotion in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Astatic
Bfunction
Cvar
Dpublic
Which PHP version introduced constructor promotion?
APHP 8.0
BPHP 5.6
CPHP 7.4
DPHP 8.1
What happens if you omit the visibility keyword in a constructor parameter?
AThe parameter is promoted as a public property
BSyntax error occurs
CThe parameter is not promoted and just acts as a normal parameter
DThe parameter becomes static
Can constructor promotion be used with readonly properties?
AYes, by adding the readonly keyword after the visibility
BNo, readonly properties cannot be promoted
COnly in PHP 7
DOnly for public properties
Which of these is a valid promoted constructor parameter?
Afunction __construct(string $name)
Bpublic function __construct(public string $name)
Cprivate function __construct(string $name)
Dprotected function __construct($name)
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.