How can data encapsulation be maintained when handling error messages in PHP registration forms?

When handling error messages in PHP registration forms, data encapsulation can be maintained by using a separate function to validate user input and return any errors. This function should only return error messages and not directly manipulate any data. By keeping the error handling separate from the data manipulation, we can ensure that data encapsulation is maintained.

function validateInput($username, $password) {
    $errors = array();

    if(strlen($username) < 5) {
        $errors[] = "Username must be at least 5 characters long.";
    }

    if(strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long.";
    }

    return $errors;
}

$username = $_POST['username'];
$password = $_POST['password'];

$errors = validateInput($username, $password);

if(!empty($errors)) {
    foreach($errors as $error) {
        echo $error . "<br>";
    }
} else {
    // Proceed with registration process
}