0

I 've noticed something I cannot explain to myself. I need a little help to check, if an inherited class uses a specific trait. To make it a little clearer, I use the following code.

trait Foo 
{
    public function say($what) 
    {
        echo $what;
        return $this;
    }
}

class A
{
    uses Foo;
}

class B extends A
{

}

I 'm aware that I should use the class_uses() method, to find all traits used by a class. Butt this does not work on inherited instances.

$b = (new B())->say('hello');

The above example echoes hello. So the trait is inherited successfully and can be used from class B.

$used = class_uses($b);
var_dump($used);

Surprisingly this outputs an empty array. I expected, that class_uses would give me something like Foo. But it does not.

$reflection = new ReflectionClass('B');
$uses = $reflection->getTraits();
var_dump($uses);

Same expectation here. But it just outputs an empty array.

Why the used trait from class A can not be seen in the inherited class B? Are there any alternatives to solve this problem?

Marcel
  • 4,854
  • 1
  • 14
  • 24
  • 2
    And for both methods there're comments on the page that they do not show traits from parent classes. – u_mulder Mar 13 '19 at 14:02
  • 3
    And even more - in comments section of `class_uses` there's a solution to get all traits. But who reads comments. – u_mulder Mar 13 '19 at 14:04
  • Okay, that was a bit embarrassing now. Thanks for the hint. I guess I was a little blinded here. – Marcel Mar 13 '19 at 14:04

1 Answers1

0

class_uses — Return the traits used by the given class.

However, you'd need to cycle through the inheritance tree to get all traits used, and through each trait as well.

To get ALL traits including those used by parent classes and other traits, use this function that I got from php documentation page in comments section here:

function class_uses_deep($class, $autoload = true) { 
    $traits = []; 
    do { 
        $traits = array_merge(class_uses($class, $autoload), $traits); 
    } while($class = get_parent_class($class)); 
    foreach ($traits as $trait => $same) { 
        $traits = array_merge(class_uses($trait, $autoload), $traits); 
    } 
    return array_unique($traits); 
}
Edison Biba
  • 4,384
  • 3
  • 17
  • 33