What is the proper way to check if a class uses a certain trait?
I just found how Laravel solves this and thought I'd share it here. It uses class_uses
beneath but goes through all the parents to find all the traits recursively.
It defines a helper function called class_uses_recursive:
function class_uses_recursive($class)
{
if (is_object($class)) {
$class = get_class($class);
}
$results = [];
foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) {
$results += trait_uses_recursive($class);
}
return array_unique($results);
}
function trait_uses_recursive($trait)
{
$traits = class_uses($trait);
foreach ($traits as $trait) {
$traits += trait_uses_recursive($trait);
}
return $traits;
}
And you can use it like this:
in_array(MyTrait::class, class_uses_recursive($class));
You can see how they use it to check if a model implements the SoftDeletes trait here:
public function throughParentSoftDeletes()
{
return in_array(SoftDeletes::class, class_uses_recursive($this->throughParent));
}