What are the potential pitfalls of using public properties in PHP classes instead of setters with preconditions?

Using public properties in PHP classes instead of setters with preconditions can lead to issues with data integrity and security. Without setters with preconditions, there is no way to validate or sanitize input before setting the property, which can result in unexpected behavior or vulnerabilities in the code. To solve this issue, it is recommended to use setters with preconditions to ensure that only valid data is set for each property.

class User {
    private $username;

    public function setUsername($username) {
        if (strlen($username) < 5) {
            throw new Exception('Username must be at least 5 characters long');
        }
        
        $this->username = $username;
    }

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

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

try {
    $user->setUsername('john');
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage(); // Output: Error: Username must be at least 5 characters long
}