How can I compare an object with the parent class in php?
-
21-09-2019 - |
Question
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();
OTHER TIPS
Yes definitely, but beware of the inheritance.
class Foo;
class Bar extends Foo;
$foo = new Foo();
if($foo instanceof Foo) // true
if($foo instanceof Bar) // false
$bar = new Bar();
if($bar instanceof Foo) // true
if($bar instanceof Bar) // true
It's very useful if you want to make sure a class implements an interface or extends abstract class (ie for plugins, adapters, ...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow