class A {}
class B extends A {}
class C extends A {}
class D extends C {}
$class="C";
if ($class instanceof A) { //This is just for demonstration - I know instanceof won't work!!!
$object=new $class("","",1)
}
How can a check the string “C” to check that this classname is a child of A?
I looked into is_a() but it doesn’t help.
I am specifically asking for “C” as I am getting the class name dynamically and I can’t instantiate without knowing what parameters to pass to constructor!
You can use PHP’s reflection class to look at class inheritance given a string name. For example, you could easily build an array of all parent classes like this:
Of course you may find this more troublesome than you instantiating an object an using
instanceof.The
ReflectionClassalso has a lot of other interesting methods that might help you since it seems you are interested in finding out properties of a class just given it’s name.Check the link for more info:
http://php.net/manual/en/class.reflectionclass.php
For example, you could get the information on parameters needed for the current class’ constructor like this: