PHP 8 interview question · Most asked

What is constructor property promotion?

Create a free account to save this page, take notes and track your progress. Sign in

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 readonly for immutable value objects
  • Constructor body still runs for validation
  • Not allowed for variadic parameters or callable types

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

← All PHP 8 questions

Was this page helpful?