【问题标题】:How can I compare an object with the parent class in php?如何将对象与 php 中的父类进行比较?
【发布时间】:2010-12-07 07:32:08
【问题描述】:

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

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

有没有更简单的方法?

【问题讨论】:

    标签: php inheritance class-names


    【解决方案1】:

    你可以使用__CLASS__magic constant:

    return get_class($obj) == __CLASS__;
    

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

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

    【讨论】:

    • 哦,我明白了! CLASS 和 get_class() 在继承方法中具有与 self 相同的行为。非常感谢!我的朋友也刚刚给了我一个优雅的解决方案:return $obj instanceof self;
    • $obj instanceof self 不起作用:$bar->compare(new bar);会是真的
    • 谢谢,这是我自己发现的!
    【解决方案2】:

    当然可以,但要注意继承。

    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
    

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

    【讨论】:

    • 我不明白,如果它有用,我为什么要小心它?
    • 因为$bar = new Bar(); if($bar instanceof Foo) 返回true,这在您的情况下可能不是预期的行为......
    • 哦,对不起,我没有完全理解你的例子。谢谢,我知道这种行为:)
    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多