How can Getter/Setter methods be utilized to enforce specific data types in PHP properties?
To enforce specific data types in PHP properties, Getter/Setter methods can be used. By creating Getter methods to retrieve the property value and Setter methods to set the property value, we can include type-checking logic within these methods to ensure that only values of the desired data type are accepted.
class User {
private $name;
public function getName() {
return $this->name;
}
public function setName($name) {
if (is_string($name)) {
$this->name = $name;
} else {
throw new InvalidArgumentException('Name must be a string');
}
}
}
$user = new User();
$user->setName('John');
echo $user->getName(); // Output: John
$user->setName(123); // Throws an exception