如何将对象与php中的父类进行比较?

时间:2009-10-16 09:10:57

标签: php inheritance class-names

我想比较一个对象的类和当前的类,并在继承的方法中引用父类。这是我能想到的唯一方法:

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

这是因为self引用了继承方法中的父类,但是每次我想进行比较时都必须实例化一个类。

有更简单的方法吗?

2 个答案:

答案 0 :(得分:4)

您可以使用__CLASS__ magic constant

return get_class($obj) == __CLASS__;

甚至只使用没有参数的get_class()

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

答案 1 :(得分:0)

肯定是,但要注意继承。

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

如果你想确保一个类实现一个接口或扩展抽象类(即插件,适配器......),这非常有用。