PHP is_subclass_An BUG and Solution for the of Function

  • 2021-06-28 11:43:22
  • OfStack

is_subclass_The role of of:

bool is_subclass_of ( object object, string class_name )

If the object object belongs to a class class_A subclass of name returns TRUE, otherwise it returns FALSE.
Note: The object parameter (class name) can also be specified with a string starting with PHP 5.0.3.

Example use:


# judge $className Is it $type Subclasses 
is_subclass_of($className,$type);

There will be one bug for interface before php 5.3.7

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

Terms of settlement:

function isSubclassOf($className, $type){
    //  If  $className  The class to which it belongs is  $type  Subclass, then returns  TRUE   
    if (is_subclass_of($className, $type)) {
        return true;
    }

    //  If php Edition >=5.3.7  Non-existent interface bug  therefore  $className  No  $type  Subclasses 
    if (version_compare(PHP_VERSION, '5.3.7', '>=')) {
        return false;
    }

    //  If $type Not an interface   Nor will there be bug  therefore  $className  No  $type  Subclasses 
    if (!interface_exists($type)) {
        return false;
    }

    //   Establish 1 Reflector objects 
    $r = new ReflectionClass($className); 
    //   Determine whether this class belongs to by reflecting objects $type Interface 
    return $r->implementsInterface($type);
}


Related articles: