How to check if a class is using a Trait?

4

How can we tell if a class uses a Trait?

For example:

trait Setter
{
   protected $vars = [];

   public function __set($key, $value)
   {
       $this->vars[$key] = $value;
   }
}

class User
{
   use Setter;
}

$user = new User;

if ($user contém o trait Setter) {
   // faça alguma coisa
}

According to the given code, how do you know that $user is using trait Setter ?

    
asked by anonymous 08.07.2015 / 18:13

2 answers

1

There is a function in PHP that is class_uses .

See the class_uses link

    
08.07.2015 / 18:28
1

Another way to find out if trait exists in a class is through the RelectionClass::getTraits

See:

$reflection = new ReflectionClass('MyClass');

if (in_array($trait, $reflection->getTraits())) {

    // Trait existe
}

Or:

$reflection = new ReflectionClass('MyClass');


if (isset($reflection->getTraits()[$trait])) {

    // Trait existe
}
    
08.07.2015 / 23:00