Recall & Review
beginner
What is the purpose of the __get magic method in PHP?
The __get method is called when reading data from non-existing properties. It allows you to control what happens when you try to access such properties.
Click to reveal answer
beginner
What does the __set magic method do in PHP?
The __set method is called when writing data to non-existing properties. It lets you define how to handle setting values to those properties.
Click to reveal answer
intermediate
How do __get and __set help with property access in PHP classes?
They let you control reading and writing to non-existing properties, making your class flexible and secure by managing property access.Click to reveal answer
beginner
Show a simple example of using __get and __set in a PHP class.
class Person {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$person = new Person();
$person->name = 'Alice';
echo $person->name; // Outputs: AliceClick to reveal answer
intermediate
What happens if you try to access a property that does not exist and __get is not defined?
PHP will trigger a notice about an undefined property and return NULL. Defining __get lets you handle this situation gracefully.
Click to reveal answer
Which magic method is called when you try to read a non-existing property in PHP?
✗ Incorrect
The __get method is triggered when reading non-existing properties.
What does the __set method allow you to do?
✗ Incorrect
The __set method is called when writing to non-existing properties.
If a class has __get and __set methods, what happens when you access a non-existing property?
✗ Incorrect
__get and __set allow controlled access to non-existing properties.
What will this code output?
class Test {
private $data = [];
public function __get($name) {
return $this->data[$name] ?? 'Not set';
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
$t = new Test();
echo $t->color;
✗ Incorrect
Since 'color' is not set, __get returns 'Not set' as defined.
Why might you use __get and __set instead of public properties?
✗ Incorrect
Using __get and __set lets you control how properties are accessed and modified.
Explain how __get and __set magic methods work in PHP and why they are useful.
Think about what happens when you try to read or write a property that is not public.
You got /4 concepts.
Write a simple PHP class using __get and __set to store property values in a private array.
Use an array inside the class to save property values dynamically.
You got /4 concepts.