In PHP, __get() and __set() are magic methods used for overloading properties — meaning they let you access or assign to inaccessible (private, protected, or non-existent) properties in an object.
Here’s the difference:
| Method | Purpose | When Called | Parameters | Return Value |
|---|---|---|---|---|
__get($name) | Retrieve the value of an inaccessible or undefined property. | When you try to read a property that is private, protected, or doesn’t exist. | $name → The name of the property being accessed. | Must return the property value. |
__set($name, $value) | Set the value of an inaccessible or undefined property. | When you try to write to a property that is private, protected, or doesn’t exist. | $name → The property name; $value → The value being assigned. | No return value required. |
Example
class Student {
private $data = [];
public function __get($name) {
echo "Getting '$name' property...\n";
return $this->data[$name] ?? null;
}
public function __set($name, $value) {
echo "Setting '$name' to '$value'...\n";
$this->data[$name] = $value;
}
}
$student = new Student();
// Writing to undefined property → calls __set()
$student->name = "Himanshu";
$student->age = 25;
// Reading undefined property → calls __get()
echo $student->name;
echo $student->age;
Output:
Setting 'name' to 'Himanshu'...
Setting 'age' to '25'...
Getting 'name' property...
Himanshu
Getting 'age' property...
25
✅ Key takeaway:
__set()is for assigning values to inaccessible properties.__get()is for retrieving values from inaccessible properties.
