Class Type Hints
Although PHP remains a loosely typed language—which means that properties are not explicitly either string, integer, or boolean—PHP 5 introduces class type hints, which allow you to specify what class of object should be passed into a method. These are not required, and are also not checked until the script is actually run; they aren't strict, by any means. Furthermore, they only work for classes right now—you can't specify, for example, that a parameter should be an integer or a string. Having said that, future versions will likely introduce the ability to request that arrays be passed in.
Here is an example of a type hint in action:
class Dog {
public function do_drool() {
echo "Sluuuuurp\n";
}
}
class Cat { }
function drool(Dog $some_dog) {
$some_dog->do_drool();
}
$poppy = new Cat();
drool($poppy);The drool() method will accept one parameter, $some_dog, but that parameter name is preceded by the class hint—I have specified that it should only accept a parameter of type Dog. In the example, I have made $poppy a Cat object, and that will give the following output:
Fatal error: Argument 1 must be an instance of dog in C:\home\classhint.php
on line 12Providing a class hint for a class type that does not exist will cause a fatal error. Class hints are essentially a way for you to skip having to use the instanceof keyword again and again to verify that your methods have received the right kind of objects. Using a class hint is essentially an implicit call to instanceof ...