PHP 8 interview question · Most asked
What is constructor property promotion?
Summary
Constructor promotion lets you declare and assign class properties directly in the constructor signature by adding a visibility modifier to the parameter.
Longer Answer
It removes the classic three-step boilerplate (declare property, declare parameter, assign in body). A promoted parameter with public, protected or private (and optionally readonly from 8.1) automatically becomes a property initialized with the argument.
You can mix promoted and normal parameters, and the constructor body still runs after promotion. Restrictions: no promotion in abstract constructors or interfaces, no variadic promotion, and callable cannot be a promoted type.
Code Example
<?php
final class Money
{
public function __construct(
public readonly int $amount,
public readonly string $currency = 'USD',
) {
if ($amount < 0) {
throw new InvalidArgumentException('Amount must be >= 0');
}
}
}
$price = new Money(1999);
echo $price->currency; // USD
Key Points
- Add a visibility modifier to promote a parameter
- Combine with
readonlyfor immutable value objects - Constructor body still runs for validation
- Not allowed for variadic parameters or
callabletypes
Explanation
Common mistakes
- Re-assigning the promoted property again in the body
- Forgetting that validation must still be written in the body
More most-asked PHP 8 questions
- How should passwords be stored in PHP?
- What are the most important features introduced in PHP 8.0?
- What are union types in PHP 8 and how do you use them?
- What are named arguments and what are their benefits and risks?
- How does `match` differ from `switch`?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- What are enums in PHP 8.1? Explain pure vs backed enums.
- Explain readonly properties (8.1) and readonly classes (8.2).