instanceof OPERATOR in PHP

By: Emiley J.  

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, instanceof is an operator and therefore can be used in expressions in conjunction to other operators (for example, the ! [negation] operator). This allows you to easily write a checkIfNotRectangle() function:

function checkIfNotRectangle($shape)

{

if (!($shape instanceof Rectangle)) {

print $shape->name;

print " is not a rectangle\n";

}

}

Note: instanceof also checks if an object implements an interface (which is also a classic is-a relationship).




Archived Comments


Most Viewed Articles (in PHP )

Installing PHP with nginx-server under windows

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to convert strings to strict booleans in PHP

Convert IP address to integer and back to IP address in PHP

Function to return number of digits of an integer in PHP

Function to force strict boolean values in PHP

Function to sort array by elements and count of element in PHP

PHP pages does not display in IIS 6 with Windows 2003

Latest Articles (in PHP)

Comment on this tutorial