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条)

报告相同问题?

悬赏问题

  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题