views:

128

answers:

4

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}
  }
+1  A: 

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.

Gopalakrishnan Subramani
A: 

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

Lukman
A: 

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

if(class_exists($classname)){
   $tmp=new $classname;
   if($obj instanceof Annotation) {//do something}
  }
streetparade
+5  A: 

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.

Gordon
+1 good one. ReflectionClass seems to overkill compared to this simpler one function call :)
Lukman
very nice! How did I miss those functions?
dnagirl
The whole point is that an interface is not dependant on the heredity of a class. In PHP (AFAIK) interfaces do not exist as first class entities so these functions may not behave the way you expect. e.g. dog, mouse and cat might implement a common interface but there may be no common base class.C.
symcbean
@symcbean Umm, and your point is? I expect these functions to do what it says in the Manual and in the description given above. Nothing more, nothing less. No one said interfaces work the same as inheritance.
Gordon