How can setters in PHP classes be used to validate and manipulate data before assigning it to a property?

Setters in PHP classes can be used to validate and manipulate data before assigning it to a property by creating setter methods that enforce specific rules or transformations on the input data. This allows for data validation and sanitization to occur before the data is stored in the class property, ensuring that only valid and correctly formatted data is stored.

class User {
    private $username;

    public function setUsername($username) {
        // Validate username format
        if (preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) {
            $this->username = $username;
        } else {
            echo "Invalid username format";
        }
    }

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

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

$user->setUsername("joh"); // Invalid username format