O'Reilly logo

PHP 5 Power Programming by Derick Rethans, Stig Sæther Bakken, Andi Gutmans

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required