1

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

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 在继承方法中引用父类,但是每次我想进行比较时都必须实例化一个类似乎有点过分。

有没有更简单的方法?

4

2 回答 2

4

您可以使用__CLASS__ 魔术常数

return get_class($obj) == __CLASS__;

甚至只使用不带参数的get_class() :

return get_class($obj) == get_class();
于 2009-10-16T09:15:25.100 回答
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

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

于 2009-10-16T09:24:56.140 回答