0

I want to know that wether is possible that I can import trait dynamically and apply to the parent class.

trait A{
 function a(){}
}

class B{
  //use A   <-no import here

  function b(){
     //Define if need trait A

     // Import A and apply to B <- Possible?
  }
}

Thank you very much for your advice!

1 Answer 1

2

No you can't. The trait is a feature of the class, and php yanks it in there, has to resolve conflicts (or find out they aren't resolved) at one time, so you define it at the class, and that's it.

You really do have to ask yourself if you want to use them like this though. If a class might or might not have a trait, is it really a class? and are you using the trait correctly? Hard to say without your usecase specifically, but I dare to guess this is almost always a code-smell.

If you are using traits in a good way, you can probably just use them for the whole class?

Sign up to request clarification or add additional context in comments.

Comments

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.