0
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?

1 Answer 1

1

Only define the class if the trait exists:

if (trait_exists('Foo')) {
    class Bar {
        use \Foo;
    }
} else {
    // define alternative Bar class or throw error
}
Sign up to request clarification or add additional context in comments.

2 Comments

Bar class still got some other works need to do, it must define
You cannot do that due to the way PHP defines classes. You could dynamically create a class at runtime: if (trait_exists('Foo')) { $bar = new class { use \Foo; /* ... */ }; }. You probably should restructure your code. Traits are probably not the solution to your issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.