How can PHP's magic methods like __get and __set be utilized effectively in handling variable names?

When dealing with dynamic variable names in PHP, magic methods like __get and __set can be used effectively to handle the retrieval and assignment of values to undefined properties. By implementing these magic methods, we can create a more flexible and dynamic approach to working with object properties.

class DynamicProperties {
    private $data = [];

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

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

$dynamicObj = new DynamicProperties();
$dynamicObj->example = "Hello, World!";
echo $dynamicObj->example; // Output: Hello, World!