PHP is_subclass_of函数的一个BUG和解决方法

yipeiwu_com5年前PHP代码库

is_subclass_of的作用:

复制代码 代码如下:
bool is_subclass_of ( object object, string class_name )

如果对象 object 所属类是类 class_name 的子类,则返回 TRUE,否则返回 FALSE。
注: 自 PHP 5.0.3 起也可以用一个字符串来指定 object 参数(类名)。

使用例子:

复制代码 代码如下:

#判断$className是否是$type的子类
is_subclass_of($className,$type);

php5.3.7版本前针对interface会有一个bug

bug:https://bugs.php.net/bug.php?id=53727

复制代码 代码如下:

interface MyInterface {}
class ParentClass implements MyInterface { }
class ChildClass extends ParentClass { }

# true
is_subclass_of('ChildClass', 'MyInterface');
# false
is_subclass_of('ParentClass', 'MyInterface');

解决办法:

复制代码 代码如下:
function isSubclassOf($className, $type){
    // 如果 $className 所属类是 $type 的子类,则返回 TRUE  
    if (is_subclass_of($className, $type)) {
        return true;
    }

    // 如果php版本>=5.3.7 不存在interface bug 所以 $className 不是 $type 的子类
    if (version_compare(PHP_VERSION, '5.3.7', '>=')) {
        return false;
    }

    // 如果$type不是接口 也不会有bug 所以 $className 不是 $type 的子类
    if (!interface_exists($type)) {
        return false;
    }

    //  创建一个反射对象
    $r = new ReflectionClass($className);
    //  通过反射对象判断该类是否属于$type接口
    return $r->implementsInterface($type);
}

相关文章

PHP递归遍历指定目录的文件并统计文件数量的方法

本文实例讲述了PHP递归遍历指定目录的文件并统计文件数量的方法。分享给大家供大家参考。具体实现方法如下: <?php //递归函数实现遍历指定文件下的目录与文件数量 f...

项目中应用Redis+Php的场景

前言 一些案例中有的同学说为什么不可以用string类型,string类型完全可以实现呀 我建议你看下我的专栏文章《Redis高级用法》,里面介绍了用hash类型的好处 商品维度计数...

PHP内置加密函数详解

Md5()加密算法 方式: 单向加密 语法: md5(string $str [, bool $raw_output = false]) $str:原始字符串 $raw_output:如...

PHP fopen()和 file_get_contents()应用与差异介绍

复制代码 代码如下: $file=fopen("11.txt","r")or exit("Unable to open file!");//fopen打开文件,如果不存在就显示打不开。...

php 重写分页器 CLinkPager的实例

php 重写分页器 CLinkPager的实例 1、自定义的分页器类放在哪里? 有两个位置可以放, 第一种是放在 protected/extensions 中,在使用是import...