doujiu5464 2017-10-27 06:13
浏览 58
已采纳

PHP以静态方式检查继承

I wonder if it is possible to check the inheritance of a class in a static way.

In cases I get just a class name with its namespace I can do:

    $oObject = new $sClassName();
    if(is_a($oObject, $sParentClassName)) { return true; }

But here it is mandatory to have an instance of that class.

The only static check I have found so far is the following:

    if(method_exists($sClassName, $sMethodNameFromParent)) { return true; }

But checking just for a method is no good, because I can't be sure whether the class in question inherited it from that specific parent, some other parent or implemented it all by itself.

Is there any way to check the inheritance in a static manner? Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dongling3243 2017-10-27 06:19
    关注

    You can use Reflection::isSubclassOf for this.

    class A {}
    class D {}
    class B extends D {}
    class C extends B {}
    
    $reflected = new ReflectionClass('C');
    
    echo $reflected->isSubclassOf('B'); // true
    echo $reflected->isSubclassOf('D'); // true
    echo $reflected->isSubclassOf('A'); // false
    

    No instance of C will be created, and will work even if the class has __construct arguments

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答