What are the advantages of accessing object properties using getters and setters in PHP?

Accessing object properties using getters and setters in PHP provides several advantages such as encapsulation, data validation, and flexibility. Getters allow controlled access to object properties, ensuring that the data is retrieved in a consistent manner. Setters enable validation of input data before setting the property value, helping to maintain data integrity. Additionally, using getters and setters allows for easy modification of the internal implementation of the class without affecting the external code that uses the object.

class User {
    private $username;

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

    public function setUsername($username) {
        // Perform data validation before setting the username
        if(strlen($username) >= 3 && strlen($username) <= 20) {
            $this->username = $username;
        } else {
            echo "Username must be between 3 and 20 characters long.";
        }
    }
}

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