1

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?

peterjwest
  • 4,294
  • 2
  • 33
  • 46

2 Answers2

4

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();
Greg
  • 316,276
  • 54
  • 369
  • 333
  • Oh I see! __CLASS__ and get_class() have the same behaviour as self in inherited methods. Thanks a lot! My friend has also just given me the elegant solution: return $obj instanceof self; – peterjwest Oct 16 '09 at 09:27
  • 1
    $obj instanceof self won't work: $bar->compare(new bar); will be true – Greg Oct 16 '09 at 09:42
  • Thanks, I've just discovered this for myself! – peterjwest Oct 20 '09 at 16:10
0

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, ...)

mike
  • 5,047
  • 2
  • 26
  • 32