0

I wonder if it is possible to check the inheritance of a class in a static way.

In cases I get just a class name with its namespace I can do:

    $oObject = new $sClassName();
    if(is_a($oObject, $sParentClassName)) { return true; }

But here it is mandatory to have an instance of that class.

The only static check I have found so far is the following:

    if(method_exists($sClassName, $sMethodNameFromParent)) { return true; }

But checking just for a method is no good, because I can't be sure whether the class in question inherited it from that specific parent, some other parent or implemented it all by itself.

Is there any way to check the inheritance in a static manner? Thanks in advance!

7
  • php.net/manual/en/reflectionclass.getparentclass.php ? Commented Oct 27, 2017 at 6:20
  • Why do you need this? Commented Oct 27, 2017 at 6:25
  • @xmike: so you suggest to use a while loop to iterate through all parents until I find the searched one or reach the root? Commented Oct 27, 2017 at 6:54
  • @axiac I've got a bunch of class names and have to pick those who inherit from a specific parent. I have no direct control of the number or types of class names. Commented Oct 27, 2017 at 6:56
  • Finding the parent class is not a goal per se. You are probably interested in the functionality provided by the parent class more than its name (that could change without affecting its functionality). You should check if the required feature is implemented by the class, not what classes it extends. Commented Oct 27, 2017 at 8:27

2 Answers 2

1

You can use Reflection::isSubclassOf for this.

class A {}
class D {}
class B extends D {}
class C extends B {}

$reflected = new ReflectionClass('C');

echo $reflected->isSubclassOf('B'); // true
echo $reflected->isSubclassOf('D'); // true
echo $reflected->isSubclassOf('A'); // false

No instance of C will be created, and will work even if the class has __construct arguments

Sign up to request clarification or add additional context in comments.

1 Comment

This works like a charm! While searching for ReflectionClass->isSubclassOf() I've stubled across is_subclass_of($sClassName, $sParentName) which works without instantiating a ReflectionClass. Does either of the two use the functionality of the other?
0
$oObject = new $sClassName();
if( get_parent_class($oObject) == $sParentClassName ) { return true; }

PHP function to get parent class name

2 Comments

This will only work if checked against a direct parent, i.e., will return false when checking for parent of a parent.
This is not a static check. This instantiates an object, which I did not want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.