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

yipeiwu_com6年前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 5.0 Pear安装方法

pear是PHP的扩展和应用程序库,包含了很多有用的类,安装好php5.0后,pear实际上并没有被安装,安装的方法如下:   1.在php目录中双击go-pear....

PHP设计模式之结构模式的深入解析

结构模式之间有许多相似之处,因为在对象模型结构中存在几种关系:类之间的继承和实现,加上对象组合,这些是PHP设计模式的主要目的。 对象组合的最大优势在于可以在运行时基于配置建立起一个关系...

PHP上传图片进行等比缩放可增加水印功能

啥也不说,直接上代码,大家可以自行添加增加水印功能: 复制代码 代码如下: <?php /** * * @author zhao jinhan * @date 2014年1月13日...

PHP实现动态添加XML中数据的方法

PHP实现动态添加XML中数据的方法

本文实例讲述了PHP实现动态添加XML中数据的方法。分享给大家供大家参考,具体如下: 前面简单讲述了xml文档的创建,这里继续讨论xml中数据的动态添加: 一. 代码 <...

php获取网卡的MAC地址支持WIN/LINUX系统

复制代码 代码如下: <?php /** 获取网卡的MAC地址原码;目前支持WIN/LINUX系统 获取机器网卡的物理(MAC)地址 **/ class GetMacAddr{ v...