PHP instanceof for traits

前端 未结 4 948
猫巷女王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:18

    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));
    }
    

提交回复
热议问题