Class type hints

Although PHP remains a loosely typed 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 introduced 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! (Edit: this was subsequently added in PHP 5.1 - hurrah!)

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.

As of PHP 5.1, your type hints can include arrays by specifying "array" as the type the function should receive.

 

Next chapter: Constructors and destructors >>

Previous chapter: Object type information

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar