How can restricting access to class attributes with get and set methods improve code maintainability in PHP?

Restricting access to class attributes with get and set methods in PHP can improve code maintainability by encapsulating the internal state of the object. This means that the internal implementation details of the class are hidden from the outside world, making it easier to modify the class without affecting other parts of the code. Additionally, using get and set methods allows for validation and logic to be applied when getting or setting the attribute, ensuring data integrity.

class User {
    private $username;

    public function getUsername() {
        return $this->username;
    }

    public function setUsername($username) {
        // Add validation logic here if needed
        $this->username = $username;
    }
}

$user = new User();
$user->setUsername("john_doe");
echo $user->getUsername(); // Output: john_doe