How can error handling be implemented effectively in PHP classes to inform users of incorrect input without compromising security or usability?
To implement error handling effectively in PHP classes, you can use exceptions to inform users of incorrect input without compromising security or usability. By throwing custom exceptions with meaningful error messages, users can easily understand what went wrong while maintaining security by not exposing sensitive information.
class User {
private $username;
public function setUsername($username) {
if (!is_string($username)) {
throw new InvalidArgumentException('Username must be a string');
}
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
}
$user = new User();
try {
$user->setUsername(123);
} catch (InvalidArgumentException $e) {
echo 'Error: ' . $e->getMessage();
}