PHP is_subclass_of函數的一個BUG和解決方案_PHP教程

來源:互聯網
上載者:User
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);
}

http://www.bkjia.com/PHPjc/778999.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/778999.htmlTechArticleis_subclass_of的作用: 複製代碼 代碼如下: bool is_subclass_of ( object object, string class_name ) 如果對象 object 所屬類是類 class_name 的子類,則返回...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.