How can the use of magic methods in PHP improve the efficiency and readability of accessing data in objects like User?

Using magic methods in PHP, such as __get() and __set(), can improve the efficiency and readability of accessing data in objects like User by allowing you to define custom behavior for getting and setting object properties. This can help encapsulate the logic for accessing data and make your code more organized and maintainable.

class User {
    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;
    }
}

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