Benjamin W
Benjamin W

Reputation: 2848

PHP check trait exists before use it

class Bar {

     //use Foo;
     if ( trait_exists('foo') ) { use \Foo; }

     public function .......
}

I need to check trait exists before "use" it, but i got error. Is anyone know how to achieve this?

Upvotes: 0

Views: 633

Answers (1)

Tatsh
Tatsh

Reputation: 3690

Only define the class if the trait exists:

if (trait_exists('Foo')) {
    class Bar {
        use \Foo;
    }
} else {
    // define alternative Bar class or throw error
}

Upvotes: 1

Related Questions