What is the purpose of using __set() in PHP classes?
The purpose of using __set() in PHP classes is to provide a way to set the value of inaccessible or non-existent properties within an object. This magic method allows you to define custom behavior when setting a property that is not directly accessible. This can be useful for implementing data validation, error checking, or other custom logic when setting properties.
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->name = "John";
echo $obj->name; // Output: John
Related Questions
- What are the best practices for populating a second dropdown menu based on the selection made in the first dropdown menu using PHP?
- What are some common functions or libraries in PHP that can be used to handle Zip files effectively?
- In what scenarios should multiple parameter names be used instead of reusing the same parameter name in a PDO query in PHP?