是否应使用反射或实例化来确定类是否存在并实现接口?

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}
  }

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.

Reflection is the safe & best way where you can validate without instantiate the object. But creating the object is not advisable if you don't need the object if it does not implement the Annotation and creation of object is more resource overhead. Using the reflection technique in this scenario make sense.

If you are continue using the object whether it implements the Annontation or not then, you can create the object and look whether it implements the Annotation interface. There is no best way, instead you can think of best practices.

Using ReflectionClass is a more elegant way IMO. Plus you don't have to instantiate your class just to do the checking.

This one is the usual way. I also use this method

if(class_exists($classname)){
   $tmp=new $classname;
   if($obj instanceof Annotation) {//do something}
  }