What is the proper way to check if a class uses a certain trait?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
It's not really clean and may not be the right solution for your case. But an alternative is to check if the object or class implements a method of the Trait (as usually you don't overwrite existing methods with Trait)
You can use
class_uses
function to get an array of all the traits used by a class.Then you check if this array has a key with the same name of the trait you're testing for.
if so, then your class is using your trait. If not, then it's not using it.
While nothing stops you from using
instanceof
with traits, the recommended approach is to pair traits with interfaces. So you'd have:Where
MyTrait
is an implementation ofMyInterface
. Then you check for the interface instead of traits like so:And you can also type hint, which you can't with traits:
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.