Search code examples
phpinheritanceclass-names

How can I compare an object with the parent class in php?


I want to compare the class of an object with the current class, and in inherited methods to refer to the parent class. This is the only way I can think of doing it:

class foo { function compare($obj) { return get_class($obj) == get_class(new self); } }
class bar extends foo { }

$foo = new foo;
$foo->compare(new foo); //true
$foo->compare(new bar); //false
$bar = new bar;
$bar->compare(new foo); //true
$bar->compare(new bar); //false

This works because self refers to the parent class in inherited methods, but it seems excessive to have to instantiate a class every time I want to make a comparison.

Is there a simpler way?


Solution

  • You can use __CLASS__ magic constant:

    return get_class($obj) == __CLASS__;
    

    Or even just use get_class() with no argument:

    return get_class($obj) == get_class();