Search

Laravel 5: Determining Which Traits a Class Uses With trait_uses_recursive

April 15, 2018 —John Koster

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.

#Signature

The signature of the trait_uses_recursive function is:

1function trait_uses_recursive(
2 $trait
3);

#Example Use

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$traits = trait_uses_recursive('ExampleClass');

The $traits variable would contain the following array:

1array {
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$classInstance = new ExampleClass;
2 
3$traits = trait_uses_recursive($classInstance);

Again, the $traits variable would contain the following values:

1array {
2 ["TraitTwo"] "TraitTwo"
3 ["TraitThree"] "TraitThree"
4 ["TraitOne"] "TraitOne"
5}

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.