How can magic methods in PHP, such as __set and __get, be utilized effectively in programming?

Magic methods in PHP, like __set and __get, can be utilized effectively to handle properties that are not directly accessible in a class. This can be helpful when you want to dynamically set or get properties without explicitly defining them in the class. By using these magic methods, you can create more flexible and dynamic code that can adapt to different scenarios.

class Example {
    private $data = [];

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

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

$example = new Example();
$example->name = 'John Doe';
echo $example->name; // Output: John Doe