View Full Version : How to check if a named class implements an interface?

01-20-2012, 01:42 PM
I know that you can use the instanceof operator or the is_a function to check to see if an object is an instance of a class or interface but that's not what I want.

Is there any way to check whether or not a named class implements an interface, without having to create an instance of the class?

For example, consider the following code:

interface myinterface {}

class mybase {}

class myclass extends mybase implements myinterface {}

var_dump(is_subclass_of("myclass", "mybase"));
var_dump(is_subclass_of("myclass", "myinterface"));

Which gives the following result:


01-20-2012, 02:16 PM

$interfaces = class_implements( 'myclass' );

if ( isset( $interfaces['myinterface'] ) )
// yessir

Or you can use class reflection:

$class = new ReflectionClass( 'myclass' );

if ( $class->implementsInterface( 'myinterface' ) )
// yessir