What are the best practices for handling user input validation and default values in PHP classes?

When handling user input validation in PHP classes, it is important to sanitize and validate the input to prevent security vulnerabilities and ensure data integrity. Setting default values for properties can help ensure that the class functions correctly even if certain inputs are missing. One common approach is to use constructor parameters to enforce validation and set default values.

class User {
    private $username;
    private $email;

    public function __construct($username, $email) {
        $this->username = $this->validateUsername($username);
        $this->email = $this->validateEmail($email);
    }

    private function validateUsername($username) {
        // Perform validation logic here
        return $username;
    }

    private function validateEmail($email) {
        // Perform validation logic here
        return $email;
    }

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

    public function getEmail() {
        return $this->email;
    }
}

// Example usage
$user = new User('john_doe', 'john.doe@example.com');
echo $user->getUsername(); // Output: john_doe
echo $user->getEmail(); // Output: john.doe@example.com