What is the difference between is_a and instanceof?
instanceof
can be used with other object instances, the class's name, or an interface. I don't think that (Update: See https://gist.github.com/1455148)is_a()
works with interfaces (only a string representing a class name), but correct me if it does.
Example from php.net:
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
outputs:
bool(true)
bool(true)
bool(false)
Here is performance results of is_a() and instanceof:
Test name Repeats Result Performance
instanceof 10000 0.028343 sec +0.00%
is_a() 10000 0.043927 sec -54.98%
Test source is here.
Update
As of PHP 5.3.9, the functionality of is_a()
has changed. The original answer below states that is_a()
must accept an Object
as the first argument, but PHP versions >= 5.3.9 now accept an optional third boolean argument $allow_string
(defaults to false
) to allow comparisons of string class names instead:
class MyBaseClass {}
class MyExtendingClass extends MyBaseClass {}
// Original behavior, evaluates to false.
is_a(MyExtendingClass::class, MyBaseClass::class);
// New behavior, evaluates to true.
is_a(MyExtendingClass::class, MyBaseClass::class, true);
The key difference in the new behavior between instanceof
and is_a()
is that instanceof
will always check that the target is an instantiated object of the specified class (including extending classes), whereas is_a()
only requires that the object be instantiated when the $allow_string
argument is set to the default value of false
.
Original
Actually, is_a
is a function, whereas instanceof
is a language construct. is_a
will be significantly slower (since it has all the overhead of executing a function call), but the overall execution time is minimal in either method.
It's no longer deprecated as of 5.3, so there's no worry there.
There is one difference however. is_a
being a function takes an object as parameter 1, and a string (variable, constant, or literal) as parameter 2. So:
is_a($object, $string); // <- Only way to call it
instanceof
takes an object as parameter 1, and can take a class name (variable), object instance (variable), or class identifier (class name written without quotes) as parameter 2.
$object instanceof $string; // <- string class name
$object instanceof $otherObject; // <- object instance
$object instanceof ClassName; // <- identifier for the class