tags:

views:

4802

answers:

2

Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?

+10  A: 
interface IInterface
{
}

class TheClass implements IInterface
{
}

$cls = new TheClass();
if ($cls instanceof IInterface)
    echo "yes"

You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.

nlaq
+9  A: 

Nelson LaQuet points out that instanceof can be used to test if the object is an instance of a class that implements an interface.

But instanceof doesn't distinguish between a class type and an interface. You don't know if the object is a class that happens to be called IInterface.

You can also use the reflection API in PHP to test this more specifically:

$class = new ReflectionClass('TheClass');
if ($class->implementsInterface('IInterface'))
{
  print "Yep!\n";
}

See http://php.net/manual/en/book.reflection.php

Bill Karwin
This can be used on "static" classes
Znarkus