Programming Tutorials

instanceof OPERATOR in PHP

By: Emiley J. in PHP Tutorials on 2008-11-22  

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






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Decrypting files using GnuPG (GPG) via PHP

Send push notifications using Expo tokens in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Count occurrences of a character in a String in PHP

Password must include both numeric and alphabetic characters - Magento

Error: Length parameter must be greater than 0

Reading word by word from a file in PHP

Parent: child process exited with status 3221225477 -- Restarting

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Floating point precision in PHP

Latest Articles (in PHP)