__set in php
In PHP, __set
is a magic method that is called when an undefined or inaccessible property is being set. It allows the developer to define custom behavior for setting the value of a property.
The __set
method has two parameters: $name
, which is the name of the property being set, and $value
, which is the value to be assigned to the property.
Here is an example of how to use __set
in PHP:
class MyClass {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
return $this->data[$name];
}
}
$obj = new MyClass();
$obj->property = 'some value'; // calls __set method
echo $obj->property; // calls __get method and outputs 'some value'
In the example above, the __set
method sets the value of the property to an associative array $data
, and the __get
method retrieves the value of the property from the $data
array.
It's important to note that __set
is only called when trying to set an undefined or inaccessible property. If the property is already defined, its value will be updated without calling the __set
method.