Interview frequency: …
Short answer
It lets you declare a property, its type and visibility, and assign it directly in the constructor (__construct) parameters without repeating the code.
Explanation
Previously, creating a property required declaring it above the constructor, accepting it as a constructor parameter, and assigning it with $this->property = $property. In PHP 8, placing public, private, or protected before a constructor parameter tells the engine to create the property and assign its value automatically.
Code example
class User {
public function __construct(
public readonly int $id,
public string $name,
private string $email
) {}
}Common mistakes
- Using constructor promotion outside the __construct method.
Follow-up questions
- What are Anonymous Classes, and when are they used in PHP?
- What are Readonly Classes in PHP 8.2, and how do they support immutable Value Objects?