Home  >  Article  >  Backend Development  >  A BUG and solution for the PHP is_subclass_of function_PHP tutorial

A BUG and solution for the PHP is_subclass_of function_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:29:10789browse

The role of is_subclass_of:

Copy code The code is as follows:
bool is_subclass_of (object object, string class_name)

If the class of object object is If the class class_name is a subclass, TRUE is returned, otherwise FALSE is returned.
Note: Since PHP 5.0.3, you can also use a string to specify the object parameter (class name).

Usage example:

Copy code The code is as follows:

# Determine whether $className is Subclass of $type
is_subclass_of($className,$type);

There will be a bug in the interface before php5.3.7 version

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

Copy code The code is as follows:

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

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

Solution:

Copy code The code is as follows:
function isSubclassOf($className, $type){
// If the class to which $className belongs is If it is a subclass of $type, return TRUE
if (is_subclass_of($className, $type)) {
return true;
}

// If php version>=5.3. 7 There is no interface bug, so $className is not a subclass of $type
if (version_compare(PHP_VERSION, '5.3.7', '>=')) {
return false;
}

// There will be no bug if $type is not an interface, so $className is not a subclass of $type
if (!interface_exists($type)) {
return false;
}

// Create a reflection object
$r = new ReflectionClass($className);
// Determine whether the class belongs to the $type interface through the reflection object
return $r->implementsInterface($ type);
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/778999.htmlTechArticleThe function of is_subclass_of: Copy the code as follows: bool is_subclass_of (object object, string class_name) If the class of object object is A subclass of class class_name, then return...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn