instanceof type operator
suggest changeFor checking whether some object is of a certain class, the (binary) instanceof operator can be used since PHP version 5.
The left operand is the value to test. If it is not an object, instanceof returns false. A quoted class name on the right, such as $o instanceof 'MyClass', is a parse error. Use a variable for a dynamic class name.
The second (right) parameter is the class to compare with. The class can be provided as the class name itself, a string variable containing the class name (not a string constant!) or an object of that class.
class MyClass {
}
$o1 = new MyClass();
$o2 = new MyClass();
$name = 'MyClass';
// in the cases below, $a gets boolean value true
$a = $o1 instanceof MyClass;
$a = $o1 instanceof $name;
$a = $o1 instanceof $o2;
// counter examples:
$b = 'b';
// $o1 instanceof 'MyClass' is a parse error; use a variable for dynamic class names.
$a = false instanceof MyClass; // false
$a = $b instanceof MyClass; // false ($b is not an object)
instanceof can also be used to check whether an object is of some class which extends another class or implements some interface:
interface MyInterface {
}
class MySuperClass implements MyInterface {
}
class MySubClass extends MySuperClass {
}
$o = new MySubClass();
// in the cases below, $a gets boolean value true
$a = $o instanceof MySubClass;
$a = $o instanceof MySuperClass;
$a = $o instanceof MyInterface;
To check whether an object is not of some class, the not operator (!) can be used:
class MyClass {
}
class OtherClass {
}
$o = new MyClass();
$a = !$o instanceof OtherClass; // true
Parentheses around $o instanceof MyClass are not required, because instanceof has higher precedence than !. Parentheses still make the expression easier to read.
Caveats
If a class does not exist, the registered autoload functions are called to try to define the class (this is a topic outside the scope of this part of the Documentation!). In PHP versions before 5.1.0, the instanceof operator would also trigger these calls, thus actually defining the class (and if the class could not be defined, a fatal error would occur). To avoid this, use a string:
// only PHP versions before 5.1.0!
class MyClass {
}
$o = new MyClass();
$a = $o instanceof OtherClass; // OtherClass is not defined!
// if OtherClass can be defined in a registered autoloader, it is actually
// loaded and $a gets boolean value false ($o is not a OtherClass)
// if OtherClass can not be defined in a registered autoloader, a fatal
// error occurs.
$name = 'YetAnotherClass';
$a = $o instanceof $name; // YetAnotherClass is not defined!
// $a simply gets boolean value false, YetAnotherClass remains undefined.
As of PHP version 5.1.0, the registered autoloaders are not called anymore in these situations.
Older versions of PHP (before 5.0)
In PHP before 5.0, is_a was the way to test an object's class. It was deprecated in PHP 5 and restored in PHP 5.3.0.