PHP instanceof for traits

前端 未结 4 947
猫巷女王i
猫巷女王i 2020-12-28 13:37

What is the proper way to check if a class uses a certain trait?

4条回答
  •  执笔经年
    2020-12-28 14:15

    While nothing stops you from using instanceof with traits, the recommended approach is to pair traits with interfaces. So you'd have:

    class Foo implements MyInterface
    {
        use MyTrait;
    }
    

    Where MyTrait is an implementation of MyInterface. Then you check for the interface instead of traits like so:

    if ($foo instanceof MyInterface) {
        ...
    }
    

    And you can also type hint, which you can't with traits:

    function bar(MyInterface $foo) {
        ...
    }
    

    In case you absolutely need to know whether a class is using a certain trait or implementation, you can just add another method to the interface, which returns a different value based on the implementation.

提交回复
热议问题