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