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

Get PHP 5 Power Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.