Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jun 2010
    Posts
    302
    Thanks
    68
    Thanked 8 Times in 8 Posts

    How to check if a named class implements an interface?

    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:

    PHP 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:

    bool(true)
    bool(false)
    Last edited by XmisterIS; 01-20-2012 at 01:46 PM.

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    http://php.net/class_implements
    PHP Code:
    $interfaces class_implements'myclass' );

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

    Or you can use class reflection:
    PHP Code:
    $class = new ReflectionClass'myclass' );

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

    Last edited by kbluhm; 01-20-2012 at 10:23 PM. Reason: Dumped in_array() for the more efficient isset()

  • Users who have thanked kbluhm for this post:

    XmisterIS (01-20-2012)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •