Corey Wu
Corey Wu

Reputation: 1159

Hack - how to check that an instance uses a Trait?

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

Upvotes: 4

Views: 2967

Answers (2)

Quetzy Garcia
Quetzy Garcia

Reputation: 1840

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
}

Upvotes: 6

zstate
zstate

Reputation: 2055

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

Upvotes: 3

Related Questions