Challenge - 5 Problems
PHP Magic Property Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of __get magic method
What is the output of this PHP code when accessing the property
$obj->name?PHP
<?php class Person { private $data = ['name' => 'Alice']; public function __get($prop) { return $this->data[$prop] ?? 'Unknown'; } } $obj = new Person(); echo $obj->name;
Attempts:
2 left
💡 Hint
The __get method returns the value from the private array if the property exists.
✗ Incorrect
The __get method intercepts access to undefined or inaccessible properties. Since 'name' exists in the private array, it returns 'Alice'.
❓ Predict Output
intermediate2:00remaining
Output when setting property with __set
What will be the output of this PHP code after setting
$obj->age = 30; and then echoing $obj->age?PHP
<?php class Person { private $data = []; public function __set($prop, $value) { $this->data[$prop] = $value; } public function __get($prop) { return $this->data[$prop] ?? 'Not set'; } } $obj = new Person(); $obj->age = 30; echo $obj->age;
Attempts:
2 left
💡 Hint
The __set method stores the value in the private array, and __get retrieves it.
✗ Incorrect
When setting $obj->age, __set stores 30 in the private array. Then __get returns 30 when accessing $obj->age.
🔧 Debug
advanced2:00remaining
Identify the error in __get usage
What error will this PHP code produce when trying to access
$obj->city?PHP
<?php class Location { private $data = ['country' => 'USA']; public function __get($prop) { return $this->data[$prop]; } } $obj = new Location(); echo $obj->city;
Attempts:
2 left
💡 Hint
Accessing an undefined array key without checking causes a notice.
✗ Incorrect
The __get method tries to return $this->data['city'], which does not exist, causing a PHP Notice for undefined index.
📝 Syntax
advanced2:00remaining
Which option causes a syntax error?
Which of the following __set method definitions will cause a syntax error in PHP?
Attempts:
2 left
💡 Hint
Check the parameter list syntax carefully.
✗ Incorrect
Option C misses a comma between parameters, causing a syntax error.
🚀 Application
expert3:00remaining
Count properties set via __set
Given this PHP class, what is the value of
$obj->count after running the code below?PHP
<?php class Counter { private $data = []; private $count = 0; public function __set($name, $value) { $this->data[$name] = $value; $this->count++; } public function __get($name) { if ($name === 'count') { return $this->count; } return $this->data[$name] ?? null; } } $obj = new Counter(); $obj->a = 1; $obj->b = 2; $obj->a = 3; echo $obj->count;
Attempts:
2 left
💡 Hint
Each __set call increments count, even if overwriting a property.
✗ Incorrect
The __set method increments count every time it is called. It is called three times, so count is 3.