xuanji
xuanji

Reputation: 5097

how to check if class instances are instanceof another class

In php, it seems that a class is not a subclass of itself

php > var_dump(is_subclass_of('Exception', 'Exception'));
bool(false)
php > var_dump(is_subclass_of('ErrorException', 'Exception'));
bool(true)

However, instances of Exception and ErrorException are both instances of Exception, and that is the property I want to check for. Is there a function I could replace is_subclass_of with that would make the output be true for both expressions?

Upvotes: 0

Views: 99

Answers (1)

Barmar
Barmar

Reputation: 780974

Define your own function that checks whether they're the same class name or one is a subclass of the other.

function same_or_subclass_of($class, $parent) {
    return $class == $parent || is_subclass_of($class, $parent);
}

Upvotes: 1

Related Questions