Mitch Mitch - 2 months ago 6
PHP Question

What's the best way to determine if a variable is a particular object?

I recently read about the difference between

is_a()
and
instanceof

I am currently using
get_class
to do an object comparison. I read that
is_a
was deprecated but brought back by popular demand even though
instanceof
is slightly faster. When would you decide to use each of these variants and why not use one of the others instead?

if (get_class($var) == 'MyObject')

if ($var instanceof \MyObject)

if (is_a($var, \MyObject))

Answer

It depends on what you really want to check.

get_class check will tell you if given object is of given class. instanceof operator on the other hand will tell you, if given object is of given class OR has that class in it's inheritance tree OR implements given interface.

Some examples:

class Parent {}
class Child extends Parent {}

$obj = new Child;

var_dump($obj instanceof Parent); // true
var_dump(get_class($obj) === 'Parent'); // false
var_dump($obj instanceof Child); // true
var_dump(get_class($obj) === 'Child'); // true

So both ways can be used depending on what you need.

Regarding is_a(), it behaves the same way as instanceof operator, but is know to be a bit slower. In bigger applications the difference in performance will be negligible.

instanceof offers more flexibility. While is_a() only accepts string as its second argument, instanceof can be passed a string, an object or class identifier.

Comments