doutouhe5343 2016-06-13 09:03
浏览 795

PHP检查实际的类是否正在实现接口

On an existing project I'm working on, we have the following situation:

interface A { }

class B implements A { }

class C extends B { }

class D extends B implements A { }

$B = new B();
$C = new C();
$D = new D();

What is the proper way to figure out if the actual class implements the interface A and not only the parent class? The check should return true for $B and $D and false for $C. Normally you would do

if( $C instanceof A ) { //do the work }

but in our situation this will return true which shouldn't.

An approach can be to parse the file and test if the class really implements A with the token_get_all function. But before doing that, I want to ask if there are more elegant solutions.

I know it sounds weird, but the situation is as it is and the class hierarchy can't be changed. Any insights would be helpful.

  • 写回答

2条回答 默认 最新

  • dongyu9894 2016-06-13 10:54
    关注

    This function returns true only if interface A is implemented not extended via parent class.

    echo checkimplements($B, "A"); //Returns True
    
    function checkimplements($class, $interfacename)
    {
        $ownInterfaces = class_implements($class);
        $parent = get_parent_class($class);
        if($parent) {
            $parentInterfaces = class_implements($parent);
        } else {
            $parentInterfaces = array();
        }
        $diff = array_diff($ownInterfaces, $parentInterfaces);
        $found = in_array($interfacename, $diff);
        return $found;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序