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);
}

相关文章

PHP7新功能总结

以下是小编给大家整理的关于PHP7的相关更新内容和知识点。 新功能 PHP 7增加了许多特性,其中最重要的特性如下所述 • 性能改进——在PHP7中合并了PHPNG代码,速度...

php下过滤html代码的函数 提高程序安全性

以下为过滤HTML代码的函数: 复制代码 代码如下: function ihtmlspecialchars($string) { if(is_array($string)) { fore...

PHP操作XML作为数据库的类

xml.class.php文件代码复制代码 代码如下: <?php * example 读取数据: * * $xml = new xml("dbase.xml",'table');...

php-cli简介(不会Shell语言一样用Shell)

1.基础知识 1.1 什么是Shell编程? 在 Unix 中,shell 可不是简单的命令解释器(典型的有 Windows 中的 DOS ),而是一个全功能的编程环境。Shell 是操...

完美解决令人抓狂的zend studio 7代码提示(content Assist)速度慢的问题

完美解决令人抓狂的zend studio 7代码提示(content Assist)速度慢的问题

最近用zend studio7.2 遇到个问题,就是打开内容很多的php页面(>500行)时,编辑保存速度奇慢。根据网络上google到的资料 ,更改了content Assist...