6.9 Class type hintsThis is NOT the latest copy of this book; click here for the latest version.
Although PHP remains a typeless language, which means you do not need to specify what types a variable is when it is declared or passed to a function, PHP 5 introduces class type hints, which allow you to specify what kind of class should be passed into a function. These are not required, and are also not checked until the script is actually run, so 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, I suspect future versions may introduce the ability to request that arrays are passed in - that's pure speculation, though!
Here is an example of a type hint in action:
<?php
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); ?>
Note that the drool() function will accept one parameter, $some_dog, but that the 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 so running that will give the following output:
Fatal error: Argument 1 must be an instance of dog in C:\home\classhint.php on line 12
Note that providing a class hint for a class type that does not exist will cause a fatal error. As you can see, class hints are essentially a way for you to skip having to use the instanceof keyword again and again to verify your functions have received the right kind of objects - using a class hint is essentially implicitly using instanceof, without the extra code. You should make use of class hints regularly as they are a very simple way to make your code regulate itself, and helps solve bugs faster.
Author's Note: As with the instanceof keyword, you can specify an interface as the class hint and only classes that that interface will be allowed through.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|