Junior — Middle
Will the __set() method be called automatically when we assign a value to an object's property?
sobes.tech AI
Answer from AI
The __set() method in PHP is called automatically only when you try to assign a value to a non-existent or inaccessible (e.g., private or protected) property of an object. If the property is declared and accessible, then __set() will not be called, and the assignment will occur directly.
Example:
class Example {
private $data = [];
public function __set($name, $value) {
echo "__set called for property '$name' with value '$value'\n";
$this->data[$name] = $value;
}
public $existingProp;
}
$obj = new Example();
$obj->existingProp = 123; // __set is not called
$obj->newProp = 456; // __set is called
In this example, assigning $obj->existingProp = 123; happens directly, while $obj->newProp = 456; calls the __set() method because newProp is not declared in the class.