Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 12

Providing 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page