dtxob80644 2016-11-29 23:26
浏览 64

如何测试类实例是否属于同一级别的父类之一?

Say I have this:

class Bird{}
class PrettyBird extends Bird{}
class UglyBird extends Bird{}
class Duckling extends UglyBird{}

and I do this:

$bird = new Duckling();

OR

$bird = new UglyBird();

Suppose in my universe all I am interested in is if class belongs to UglyBird or PrettyBird. In case above, I want to test whether $bird belongs to UglyBird (super)class in both cases above.

How?

Currently I can do it by

if (get_class($bird) === UglyBird::class 
    or get_class($bird) === Duckling::class)
    print "MATCH!";

but that's impractical. For example, what if I create a new class that extends UglyBird. I will have to add that class into the if statement.

  • 写回答

3条回答 默认 最新

  • doucuyu2259 2016-11-29 23:34
    关注

    You can use the function is_subclass_of:

    $bird = new Duckling();
    $bird2 = new PrettyBird();
    
    var_dump(is_subclass_of($bird, 'UglyBird')); // True
    var_dump(is_subclass_of($bird2, 'UglyBird')); // False
    

    Suppose you have a child class of PrettyBird:

    class PrettyDuckling extends PrettyBird{}
    

    And you want to know if the child of PrettyBird is a subclass of UglyBird:

    $bird3 = new PrettyDuckling();
    var_dump(is_subclass_of($bird3, 'PrettyBird')); // True
    var_dump(is_subclass_of($bird3, 'UglyBird')); // False
    

    Note that this will work for the parent of the parent as well:

    var_dump(is_subclass_of($bird, 'Bird')); // True
    var_dump(is_subclass_of($bird2, 'Bird')); // True
    var_dump(is_subclass_of($bird3, 'Bird')); // True
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大