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
2008-11-08 04:27:41
+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";
}
Bill Karwin
2008-11-08 07:00:31
This can be used on "static" classes
Znarkus
2009-08-23 09:41:06