How to check if a class is using a Trait?

Asked

Viewed 68 times

4

How can we know 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 to know that $user is using the trait Setter?

  • 1

    Wallace today is too much with the questions :) +1

  • 1

    Sometimes I already know the answer to some, but I ask only to have in SOPT :)

  • I know Wallace :)

2 answers

1

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

Behold:

$reflection = new ReflectionClass('MyClass');

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

    // Trait existe
}

Or:

$reflection = new ReflectionClass('MyClass');


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

    // Trait existe
}

1


There is a function in PHP that is class_uses.

Check the link class_uses

  • So, so, we have to the php 5.4 > the following way to check whether there is isset(class_uses($user, true)['TraitUser']);

  • @Wallacemaxters something is going on for my response to have been changed after you validated it

  • In fact, the classe_uses was without the ``

  • http://answall.com/posts/73452/revisions

  • without any problem... the question is yours and the answer was short and direct because I have nothing else to add. Since your preference goes to the Reflectionclass solution I do not recommend it in production code. so my answer in my opinion is possible within the question made... the rest is up to you. no drama!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.