Checking if an instance's class implements an interface?

前端 未结 6 1188
误落风尘
误落风尘 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 21:52

    Update

    The is_a function is missing here as alternative.

    I did some performance tests to check which of the stated ways is the most performant.

    Results over 100k iterations

          instanceof [object] took   7.67 ms | +  0% | ..........
                is_a [object] took  12.30 ms | + 60% | ................
                 is_a [class] took  17.43 ms | +127% | ......................
    class_implements [object] took  28.37 ms | +270% | ....................................
           reflection [class] took  34.17 ms | +346% | ............................................
    

    Added some dots to actually "feel" see the difference.

    Generated by this: https://3v4l.org/8Cog7

    Conclusion

    In case you have an object to check, use instance of like mentioned in the accepted answer.

    In case you have a class to check, use is_a.

    Bonus

    Given the case you want to instantiate a class based on an interface you require it to have, it is more preformant to use is_a. There is only one exception - when the constructor is empty.

    Example: is_a(, , true);

    It will return bool. The third parameter "allow_string" allows it to check class names without instantiating the class.

提交回复
热议问题