What are the best practices for using Getter/Setter methods to enforce type checking in PHP classes?

Using Getter/Setter methods in PHP classes can help enforce type checking by allowing you to control the data being set and retrieved from class properties. By defining specific data types for properties and using getters/setters to validate input, you can ensure that only the correct types of data are stored in your class.

class User {
    private $name;

    public function setName(string $name) {
        $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 result in a type error
$user->setName(123); // Fatal error: Uncaught TypeError: Argument 1 passed to User::setName() must be of the type string, integer given