Challenge - 5 Problems
Constructor Promotion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a class using constructor promotion
What is the output of this PHP code using constructor promotion?
PHP
<?php class User { public function __construct( public string $name, public int $age ) {} } $user = new User("Alice", 30); echo $user->name . ' is ' . $user->age . ' years old.';
Attempts:
2 left
💡 Hint
Constructor promotion automatically creates and assigns properties.
✗ Incorrect
The constructor promotion syntax creates public properties $name and $age and assigns the passed values. So accessing $user->name and $user->age works as expected.
❓ Predict Output
intermediate2:00remaining
Output when mixing promoted and non-promoted properties
What will this PHP code output?
PHP
<?php class Product { public string $category; public function __construct( public string $name, public float $price ) { $this->category = "General"; } } $p = new Product("Book", 12.5); echo $p->name . ' costs $' . $p->price . ' in category ' . $p->category;
Attempts:
2 left
💡 Hint
Non-promoted properties must be initialized manually.
✗ Incorrect
The property $category is declared but not promoted, so it is initialized inside the constructor. The promoted properties $name and $price are automatically assigned.
🔧 Debug
advanced2:00remaining
Identify the error in constructor promotion usage
What error does this PHP code produce?
PHP
<?php class Car { public function __construct( private string $make, protected int $year = 2020, public $model ) {} } $car = new Car("Toyota", 2018, "Corolla"); echo $car->make;
Attempts:
2 left
💡 Hint
Private properties cannot be accessed directly outside the class.
✗ Incorrect
The property $make is private, so trying to echo $car->make outside the class causes a fatal error due to visibility.
📝 Syntax
advanced2:00remaining
Which option causes a syntax error in constructor promotion?
Which of these constructor declarations will cause a syntax error in PHP?
Attempts:
2 left
💡 Hint
In PHP, parameters with default values must come after parameters without defaults.
✗ Incorrect
Option A has a parameter with a default value ($x) before a parameter without a default ($y), which is invalid syntax.
🚀 Application
expert2:00remaining
Count properties created by constructor promotion
How many properties does this PHP class have after construction?
PHP
<?php class Employee { public string $department = "HR"; public function __construct( public string $name, private int $id, protected float $salary = 50000.0 ) {} } $emp = new Employee("John", 1234);
Attempts:
2 left
💡 Hint
Count all declared properties including promoted and non-promoted.
✗ Incorrect
The class has one non-promoted property $department and three promoted properties: $name, $id, $salary. Total is 4 properties.