How can strict type hints and type validation be implemented in PHP setters to ensure data integrity?
Strict type hints and type validation in PHP setters can be implemented by specifying the expected data type in the setter parameter and validating the input data before setting the property. This ensures that only the correct data type is accepted, improving data integrity and reducing the risk of unexpected errors.
class User {
private string $name;
public function setName(string $name): void {
// Validate input data before setting the property
if (!is_string($name)) {
throw new InvalidArgumentException('Name must be a string');
}
$this->name = $name;
}
public function getName(): string {
return $this->name;
}
}
$user = new User();
$user->setName('John Doe');
echo $user->getName(); // Output: John Doe
// Trying to set an integer value will throw an exception
$user->setName(123);