我要比较的类与当前类的对象,并且在继承的方法来指代父类。这是我能想到这样做的唯一方法:

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

这个作品是因为自我是指在继承方法的父类,但它似乎过多有我想要做一个比较,每次实例化一个类。

有没有更简单的方式?

有帮助吗?

解决方案

可以使用__CLASS__ 魔恒定

return get_class($obj) == __CLASS__;

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

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

其他提示

是肯定的,但要注意的继承的。

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

,如果你想确保一个类实现一个接口是非常有用的,要么扩展抽象类(即用于插件,适配器,...)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top