How does the use of __set() differ from regular setters in PHP classes?

The use of __set() in PHP classes allows you to dynamically set properties on an object without explicitly defining setters for each property. This can be useful when working with classes that have a large number of properties or when you want to allow for flexibility in setting properties. Regular setters, on the other hand, require you to define a separate method for each property you want to set, which can be more time-consuming and less flexible.

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";
$obj->age = 30;

echo $obj->name; // Output: John
echo $obj->age; // Output: 30