4

How can I check if a an instance of a class uses a Trait? I can't use instanceof because the Trait is uninstantiable.

Corey Wu
  • 1,209
  • 1
  • 22
  • 39
  • As an alternative, create an interface such as `HasTrait` and make all classes that use this trait implement this interface, then check that the class instance is an instance of this interface. – Michael Dec 26 '22 at 11:53

2 Answers2

6

Hack is a super set of PHP (and also a sub set, given some legacy stuff was removed), so most of the native functions can be used.

With that being said, you have the class_uses() function, that does what you want.

Here's a simplified use case:

if (in_array(\Foo\Bar::class, class_uses($object))) {
    // Do something if $object is using \Foo\Bar trait
}
Quetzy Garcia
  • 1,820
  • 1
  • 21
  • 23
3

You can use ReflectionObject with getTraits or getTraitNames functions:

trait test {
    public function hello()
    {
        echo "hello";
    }
}

class A {
    use test;
}

function hasTrait($object, $traitName)
{
    $reflection = new ReflectionObject($object);

    return in_array($traitName, $reflection->getTraitNames());
}

$a = new A();

if(hasTrait($a, 'test')) {
    echo "Object of class 'A' has 'test' trait \n";
}
zstate
  • 1,995
  • 1
  • 18
  • 20