How can the use of __set() and __get() methods improve the code structure in PHP classes?

Using the magic methods __set() and __get() in PHP classes can improve code structure by allowing for more controlled access to class properties. These methods enable getter and setter functionality, which can help enforce data encapsulation and provide a cleaner way to interact with class properties.

class User {
    private $name;
    
    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }
    
    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
    }
}

$user = new User();
$user->name = "John Doe";
echo $user->name;