문제

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?

도움이 되었습니까?

해결책

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();

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top