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

前端 未结 3 1790
轮回少年
轮回少年 2021-01-05 11:35

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
            


        
3条回答
  •  感情败类
    2021-01-05 11:52

    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

提交回复
热议问题