Mitch Mitch - 1 year ago 40
PHP Question

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

I recently read about the difference between


I am currently using
to do an object comparison. I read that
was deprecated but brought back by popular demand even though
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 Source

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.