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.11. instanceof Operator

The instanceof operator was added as syntactic sugar instead of the already existing is_a() built-in function (which is now deprecated). Unlike the latter, instanceof is used like a logical binary operator:

class Rectangle {
    public $name = __CLASS__;
}

class Square extends Rectangle {
    public $name = __CLASS__;
}

class Circle {
    public $name = __CLASS__;
}

function checkIfRectangle($shape)
{
    if ($shape instanceof Rectangle) {
        print $shape->name;
        print " is a rectangle\n";
    }
}

checkIfRectangle(new Square());
checkIfRectangle(new Circle());

This small program prints 'Square is a rectangle\n'. Note the use of __CLASS__, which is a special constant that resolves to the name of the current class.

As previously mentioned, ...

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