QA
Intermediate LevelPHP 8+

How does PHP 8.0 Constructor Property Promotion reduce boilerplate class code?

❓ Interview Prompt: Explain PHP 8.0 Constructor Property Promotion syntax, combining visibility modifiers in parameters, and default values.

In PHP 7, declaring class properties required writing every property name three times: once for property declaration, once in the constructor parameters, and once for property assignment ('$this->prop = $prop').

Constructor Property Promotion (PHP 8.0+):

Prefixing constructor arguments with visibility modifiers ('public', 'protected', 'private', or 'readonly') instructs PHP to automatically declare the property and assign the parameter value in one single statement!

Code Implementation Example

php
<?php
// PHP 8.0+ Constructor Property Promotion
class UserDTO {
    public function __construct(
        public string $name,
        public string $email,
        private readonly int $id,
        public string $role = 'guest'
    ) {}
}

$user = new UserDTO('Alice', 'alice@co.com', 42);
echo $user->name; // Outputs: Alice
💡Reducing DTO boilerplate code using PHP 8.0 Constructor Property Promotion.
🎯 Interview Key Takeaway

Constructor Property Promotion combines property declaration, type hinting, and assignment directly in constructor parameters.

#Property Promotion#PHP 8.0#OOP#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?