What are the advantages of using 'magic' methods in PHP classes for setting and getting class variables?

Using magic methods like __get and __set in PHP classes allows for more dynamic and flexible handling of class variables. This can be useful when you want to enforce certain rules or logic when setting or getting class variables. It also makes the code more readable and maintainable by encapsulating the logic within the class itself.

class MyClass {
    private $data = [];

    public function __get($name) {
        return $this->data[$name];
    }

    public function __set($name, $value) {
        // Add any validation or logic here
        $this->data[$name] = $value;
    }
}

$myObject = new MyClass();
$myObject->name = "John";
echo $myObject->name; // Output: John