Laravel 5: Determining Which Traits a Class Uses With trait_uses_recursive

Laravel 5: Determining Which Traits a Class Uses With trait_uses_recursive

Laravel 5

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:

function trait_uses_recursive(
    $trait
);

Example Use

Given the traits and class:

<?php

trait TraitOne { }

trait TraitTwo {
    use TraitOne;
}

trait TraitThree { }

trait TraitFour { }

class ExampleBaseClass {
    use TraitFour;
}

class ExampleClass extends ExampleBaseClass {
    use TraitTwo, TraitThree;
}

The traits used by ExampleClass can be determined by:

$traits = trait_uses_recursive('ExampleClass');

The $traits variable would contain the following array:

{language=php} ```php %% <?php array { ["TraitTwo"] "TraitTwo" ["TraitThree"] "TraitThree" ["TraitOne"] "TraitOne" }


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: ```php $classInstance = new ExampleClass; $traits = trait_uses_recursive($classInstance);

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

array {
    ["TraitTwo"]   "TraitTwo"
    ["TraitThree"] "TraitThree"
    ["TraitOne"]   "TraitOne"
}

Start the Discussion

Leave a comment

Subscribe to our newsletter