Checking if an instance's class implements an interface?

前端 未结 6 1192
误落风尘
误落风尘 2020-12-12 21:09

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 opt

6条回答
  •  醉话见心
    2020-12-12 22:05

    As therefromhere points out, you can use class_implements(). Just as with Reflection, this allows you to specify the class name as a string and doesn't require an instance of the class:

    interface IInterface
    {
    }
    
    class TheClass implements IInterface
    {
    }
    
    $interfaces = class_implements('TheClass');
    
    if (isset($interfaces['IInterface'])) {
        echo "Yes!";
    }
    

    class_implements() is part of the SPL extension.

    See: http://php.net/manual/en/function.class-implements.php

    Performance Tests

    Some simple performance tests show the costs of each approach:

    Given an instance of an object

    Object construction outside the loop (100,000 iterations)
     ____________________________________________
    | class_implements | Reflection | instanceOf |
    |------------------|------------|------------|
    | 140 ms           | 290 ms     | 35 ms      |
    '--------------------------------------------'
    
    Object construction inside the loop (100,000 iterations)
     ____________________________________________
    | class_implements | Reflection | instanceOf |
    |------------------|------------|------------|
    | 182 ms           | 340 ms     | 83 ms      | Cheap Constructor
    | 431 ms           | 607 ms     | 338 ms     | Expensive Constructor
    '--------------------------------------------'
    

    Given only a class name

    100,000 iterations
     ____________________________________________
    | class_implements | Reflection | instanceOf |
    |------------------|------------|------------|
    | 149 ms           | 295 ms     | N/A        |
    '--------------------------------------------'
    

    Where the expensive __construct() is:

    public function __construct() {
        $tmp = array(
            'foo' => 'bar',
            'this' => 'that'
        );  
    
        $in = in_array('those', $tmp);
    }
    

    These tests are based on this simple code.

提交回复
热议问题