Should reflection or instantiation be used to determine if a class exists and implements an interface?
oop, php, reflection
Solution
Check out these functions
- class_implements return the interfaces which are implemented by the given class
- class_parents return the parent classes of the given class
- is_a checks if the object is of this class or has this class as one of its parents
I'd prefer these over the `Reflection` class for introspection of a class or instance thereof. The Reflection API is for reverse-engineering classes.
There is also a number of other userful native function like interface_exists or property_exists, etc.
Problem
I want to determine if a class exists and whether or not it implements an interface. Both of the below should work. Which should be preferred and why? //check if class exists, instantiate it and find out if it implements Annotation ``` if(class_exists($classname)){ $tmp=new $classname; if($obj instanceof Annotation) {//do something} } ``` //check if class exists, make a reflection of it and find out if it implements Annotation ``` if(class_exists($classname)){ $r=new new ReflectionClass($classname); if($r->implementsInterface('Annotation)) {//do something} } ```