1.2.1337. Use Instanceof¶
The instanceof
operator is a more precise alternative to is_object()
. It is also faster.
instanceof checks for an variable to be of a class or its parents or the interfaces it implements.
Once instanceof
has been used, the actual attributes available (properties, constants, methods) are known, unlike with is_object()
.
Last, instanceof
may be upgraded to Typehint, by moving it to the method signature.
instanceof
and is_object()
may not be always interchangeable. Consider using isset() on a known property for a simple check on objects. You may also consider is_string(), is_integer() or is_scalar(), in particular instead of !`is_object() <https://www.php.net/is_object>`_
.
The instanceof
operator is also faster than the is_object()
functioncall.
<?php
class Foo {
// Don't use is_object
public function bar($o) {
if (!is_object($o)) { return false; } // Classic argument check
return $o->method();
}
// use instanceof
public function bar($o) {
if ($o instanceof myClass) { // Now, we know which methods are available
return $o->method();
}
return false; } // Default behavior
}
// use of typehinting
// in case $o is not of the right type, exception is raised automatically
public function bar(myClass $o) {
return $o->method();
}
}
?>
See also Type Operators and is_object.
1.2.1337.1. Connex PHP features¶
1.2.1337.1.1. Suggestions¶
Use instanceof and remove is_object()
Create a high level interface to check a whole family of classes, instead of testing them individually
Use typehint when possible
Avoid mixing scalar types and objects in the same variable
1.2.1337.1.2. Specs¶
Short name |
Classes/UseInstanceof |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
High |
Examples |
|
Available in |