views:

50

answers:

2

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?

+4  A: 

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
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
$obj instanceof self won't work: $bar->compare(new bar); will be true
Greg
Thanks, I've just discovered this for myself!
peterjwest
A: 

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

michal kralik
I don't understand, if its useful why should I beware it?
peterjwest
Because `$bar = new Bar(); if($bar instanceof Foo)` returns true which might not be expected behavior in your case...
michal kralik
Oh sorry, I didn't quite get your example. Thanks, I am aware of that behaviour :)
peterjwest