By John Koster
trait_uses_recursive($trait)
The trait_uses_recursive
function will return an array of all the traits that are used by a class. It will also return any traits that the traits are using.
Given the traits and class:
1<?php
2
3trait TraitOne { }
4
5trait TraitTwo {
6 use TraitOne;
7}
8
9trait TraitThree { }
10
11trait TraitFour { }
12
13class ExampleBaseClass {
14 use TraitFour;
15}
16
17class ExampleClass extends ExampleBaseClass {
18 use TraitTwo, TraitThree;
19}
The traits used by ExampleClass
can be determined by:
1<?php
2
3$traits = trait_uses_recursive('ExampleClass');
The $traits
variable would contain the following array:
1array(3) {
2 ["TraitTwo"] "TraitTwo"
3 ["TraitThree"] "TraitThree"
4 ["TraitOne"] "TraitOne"
5}
It should be noted that TraitFour
used by ExampleClass
's base class is not listed. The trait_uses_recursive
only lists the traits in the immediate class.
The trait_uses_recursive
function also works on class instances:
1<?php
2
3$classInstance = new ExampleClass;
4
5$traits = trait_uses_recursive($classInstance);
Again, the $traits
variable would contain the following values:
1array(3) {
2 ["TraitTwo"] "TraitTwo"
3 ["TraitThree"] "TraitThree"
4 ["TraitOne"] "TraitOne"
5}
∎