Section 3.20. Class Type Hints in Function Parameters

3.20. Class Type Hints in Function Parameters

Although PHP is not a strictly typed language in which you would need to declare what type your variables are, it does allow you (if you wish) to specify the class you are expecting in your function's or method's parameters.

Here's the code of a typical PHP function, which accepts one function parameter and first checks if it belongs to the class it requires:

 function onlyWantMyClassObjects($obj) {     if (!($obj instanceof MyClass)) {         die("Only objects of type MyClass can be sent to this function");     }     ... } 

Writing code that verifies the object's type in each relevant function can be a lot of work. To save you time, PHP enables you to specify the class of the parameter in front of the parameter itself.

Following is the same example using class type hints:

 function onlyWantMyClassObjects(MyClass $obj) {     // ... } 

When the function is called, PHP automatically performs an instanceof check before the function's code starts executing. If it fails, it will abort with an error. Because the check is an instanceof check, it is legal to send any object that satisfies the is-a relationship with the class type. This feature is mainly useful during development, because it helps ensure that you aren't passing objects to functions which weren't designed to handle them.

    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: