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: Alice
Click 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?
A__get
B__set
C__call
D__construct
✗ Incorrect
The __get method is triggered when reading non-existing properties.
What does the __set method allow you to do?
AControl how to read properties
BControl how to write to properties
CCall methods dynamically
DInitialize the object
✗ 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?
A__get and __set handle the access
BPHP throws a fatal error
CThe property is accessed directly
DThe property is ignored
✗ 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;
ANULL
Bcolor
CNot set
DError
✗ Incorrect
Since 'color' is not set, __get returns 'Not set' as defined.
Why might you use __get and __set instead of public properties?
ATo make code slower
BTo make properties global
CTo avoid writing any code
DTo control and validate property access
✗ 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.
Practice
(1/5)
1.
What is the main purpose of the __get magic method in PHP?
easy
A. To control reading of inaccessible or undefined properties
B. To delete object properties
C. To initialize object properties automatically
D. To overload methods dynamically
Solution
Step 1: Understand the role of __get
The __get method is called when reading a property that is inaccessible or not defined in the object.
Step 2: Compare with other options
Options B, C, and D describe different behaviors unrelated to __get. Only To control reading of inaccessible or undefined properties correctly describes its purpose.
Final Answer:
To control reading of inaccessible or undefined properties -> Option A
Quick Check:
__get reads missing properties = A [OK]
Hint: Remember __get triggers on reading missing properties [OK]
Common Mistakes:
Confusing __get with __set
Thinking __get initializes properties
Assuming __get deletes properties
2.
Which of the following is the correct syntax to define the __set magic method in a PHP class?
class Example {
?
}
easy
A. public function __set($name, $value) { /* code */ }
B. public function __set($value, $name) { /* code */ }
C. public function __set() { /* code */ }
D. public function set($name, $value) { /* code */ }
Solution
Step 1: Recall __set method signature
The __set method must accept two parameters: the property name and the value to assign.
Step 2: Check parameter order and method name
public function __set($name, $value) { /* code */ } correctly uses __set($name, $value). public function __set($value, $name) { /* code */ } reverses parameters, C has no parameters, and D uses wrong method name.
Final Answer:
public function __set($name, $value) { /* code */ } -> Option A
Quick Check:
__set($name, $value) correct signature = B [OK]
Hint: __set always takes property name first, then value [OK]
Common Mistakes:
Swapping parameter order
Omitting parameters
Using wrong method name without double underscore
3.
What will be the output of the following PHP code?
class Test {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name] ?? 'Not found';
}
}
$obj = new Test();
$obj->color = 'red';
echo $obj->color . ' ' . $obj->size;
medium
A. red null
B. red Not found
C. Notice error and red
D. red
Solution
Step 1: Understand property setting
Setting $obj->color = 'red' calls __set, storing 'red' in $data['color'].
Step 2: Understand property getting
Accessing $obj->color returns 'red'. Accessing $obj->size returns 'Not found' because $data['size'] is not set.
Final Answer:
red Not found -> Option B
Quick Check:
Defined property returns value, undefined returns 'Not found' = D [OK]
Hint: Undefined property returns default from __get using ?? operator [OK]
Common Mistakes:
Expecting undefined property to be empty string
Ignoring null coalescing operator
Assuming Notice error on missing array key
4.
Consider this PHP class:
class Sample {
private $props = [];
public function __set($name, $value) {
$this->props[$name] = $value;
}
public function __get($name) {
return $this->props[$name];
}
}
$obj = new Sample();
echo $obj->missing;
What error will occur and how to fix it?
medium
A. No error; outputs empty string
B. Fatal error; fix by declaring property publicly
C. Parse error; fix by adding return type
D. Undefined index notice; fix by using null coalescing in __get
Solution
Step 1: Identify error cause
Accessing $obj->missing calls __get, which returns $this->props['missing']. Since 'missing' key is not set, PHP raises an undefined index notice.
Step 2: Fix the error
Modify __get to return $this->props[$name] ?? null or a default value to avoid notice.
Final Answer:
Undefined index notice; fix by using null coalescing in __get -> Option D
Quick Check:
Missing key causes notice; use ?? to fix = C [OK]
Hint: Use ?? operator in __get to avoid undefined index notices [OK]
Common Mistakes:
Ignoring undefined index notices
Trying to declare missing properties publicly
Confusing parse errors with runtime notices
5.
You want to create a PHP class that stores any property set dynamically and logs every property read or write. Which implementation correctly uses __get and __set to achieve this?
class Logger {
private $data = [];
public function __set($name, $value) {
// ???
}
public function __get($name) {
// ???
}
}
hard
A. In __set: echo write log only; in __get: return value without logging
B. In __set: only store value; in __get: return value without logging
C. In __set: store value and echo write log; in __get: echo read log and return value or null
D. In __set: store value and return it; in __get: echo read log only
Solution
Step 1: Understand logging requirements
We must log both property writes and reads, and store values dynamically.
Step 2: Check each option's behavior
In __set: store value and echo write log; in __get: echo read log and return value or null stores the value in $data and echoes a write log in __set, and echoes a read log and returns the stored value or null in __get. This meets all requirements.
Final Answer:
In __set: store value and echo write log; in __get: echo read log and return value or null -> Option C
Quick Check:
Store and log on read/write = A [OK]
Hint: Log inside both __get and __set while storing values [OK]
Common Mistakes:
Logging only on write or only on read
Not returning value in __get
Returning value in __set (which should be void)
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.