Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[PHP]How to check if a class inherits another class without instantiating it?

Tags:

types

php

class

I have some class name. How to check if a class inherits another class without instantiating it?

 if (!class_exists($controller)) //AND I have check type
        {

            $objectController = new IndexController();
            $objectController->index();
        }
like image 709
BILL Avatar asked Jan 10 '12 16:01

BILL


2 Answers

You can use is_subclass_of:

http://php.net/manual/en/function.is-subclass-of.php

class TestA {}
class TestB extends TestA {}
class TestC extends TestB {}

var_dump(is_subclass_of('TestA', 'TestA')); // false
var_dump(is_subclass_of('TestB', 'TestA')); // true
var_dump(is_subclass_of('TestC', 'TestA')); // true
like image 165
RichardTowers Avatar answered Oct 11 '22 12:10

RichardTowers


I know this is an old question, though it ranks high on Google right now and brought me here while looking for an alternative to reflection. After not finding any, I decided to post a working example for all here.

You can do this by using reflection. Try not to rely on reflection too much since it can be resource-intensive.

class TestA {}
class TestB extends TestA {}
class TestC extends TestA {}

$reflector = new ReflectionClass('TestA');
$result    = $reflector->isSubclassOf('TestA');
var_dump($result); // false

$reflector = new ReflectionClass('TestB');
$result    = $reflector->isSubclassOf('TestA');
var_dump($result); // true

$reflector = new ReflectionClass('TestC');
$result    = $reflector->isSubclassOf('TestA');
var_dump($result); // false

For more info on class reflection, see http://www.php.net/manual/en/class.reflectionclass.php

For more info on reflection in general, see http://php.net/reflection

like image 45
Maurice Avatar answered Oct 11 '22 12:10

Maurice