These magic methods let you control what happens when you read or write properties that don't exist or are not accessible in an object.
__get and __set for property access in PHP
public function __get(string $name) { // code to return a value for $name } public function __set(string $name, $value): void { // code to set $value for $name }
__get is called automatically when reading a property that is not accessible.
__set is called automatically when writing to a property that is not accessible.
<?php class Example { private $data = []; public function __get(string $name) { return $this->data[$name] ?? null; } public function __set(string $name, $value): void { $this->data[$name] = $value; } } $obj = new Example(); $obj->color = 'red'; echo $obj->color; ?>
<?php class Person { private $name = 'Alice'; public function __get(string $name) { if ($name === 'name') { return $this->name; } return null; } public function __set(string $name, $value): void { if ($name === 'name') { $this->name = $value; } } } $p = new Person(); echo $p->name; // reads private property via __get $p->name = 'Bob'; // sets private property via __set echo $p->name;
This program shows how __get and __set work by printing messages when properties are accessed or set. It stores values in an internal array.
<?php class MagicBox { private $items = []; public function __get(string $key) { echo "Getting '$key'\n"; return $this->items[$key] ?? 'Not found'; } public function __set(string $key, $value): void { echo "Setting '$key' to '$value'\n"; $this->items[$key] = $value; } } $box = new MagicBox(); $box->fruit = 'apple'; echo $box->fruit . "\n"; echo $box->vegetable . "\n";
If you try to access a property that exists and is public, __get and __set are not called.
Use __get and __set carefully because they can hide bugs if properties are misspelled.
__get and __set let you control reading and writing of inaccessible or missing properties.
They help make flexible and dynamic objects.
Remember to handle missing properties gracefully inside these methods.
Practice
What is the main purpose of the __get magic method in PHP?
Solution
Step 1: Understand the role of
The__get__getmethod 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 AQuick Check:
__getreads missing properties = A [OK]
- Confusing __get with __set
- Thinking __get initializes properties
- Assuming __get deletes properties
Which of the following is the correct syntax to define the __set magic method in a PHP class?
class Example {
?
}Solution
Step 1: Recall
The__setmethod signature__setmethod 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 AQuick Check:
__set($name, $value)correct signature = B [OK]
- Swapping parameter order
- Omitting parameters
- Using wrong method name without double underscore
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;Solution
Step 1: Understand property setting
Setting$obj->color = 'red'calls__set, storing 'red' in$data['color'].Step 2: Understand property getting
Accessing$obj->colorreturns 'red'. Accessing$obj->sizereturns 'Not found' because$data['size']is not set.Final Answer:
red Not found -> Option BQuick Check:
Defined property returns value, undefined returns 'Not found' = D [OK]
- Expecting undefined property to be empty string
- Ignoring null coalescing operator
- Assuming Notice error on missing array key
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?
Solution
Step 1: Identify error cause
Accessing$obj->missingcalls__get, which returns$this->props['missing']. Since 'missing' key is not set, PHP raises an undefined index notice.Step 2: Fix the error
Modify__getto return$this->props[$name] ?? nullor a default value to avoid notice.Final Answer:
Undefined index notice; fix by using null coalescing in __get -> Option DQuick Check:
Missing key causes notice; use ?? to fix = C [OK]
- Ignoring undefined index notices
- Trying to declare missing properties publicly
- Confusing parse errors with runtime notices
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) {
// ???
}
}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$dataand 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 CQuick Check:
Store and log on read/write = A [OK]
- Logging only on write or only on read
- Not returning value in __get
- Returning value in __set (which should be void)
Ready to prove it?
Pass the test and this pattern moves unknown
