0
0
PHPprogramming~5 mins

Trait declaration and usage in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a trait in PHP?
A trait is a way to reuse code in multiple classes. It lets you group methods that can be included in different classes without using inheritance.
Click to reveal answer
beginner
How do you declare a trait in PHP?
Use the keyword <code>trait</code> followed by the trait name and curly braces containing methods. Example:<br><pre>trait Logger { public function log($msg) { echo $msg; } }</pre>
Click to reveal answer
beginner
How do you use a trait inside a class?
Inside the class, use the keyword <code>use</code> followed by the trait name. This adds the trait's methods to the class.<br><pre>class User { use Logger; }</pre>
Click to reveal answer
intermediate
Can a class use multiple traits? How?
Yes, a class can use multiple traits by listing them separated by commas inside the <code>use</code> statement.<br><pre>class User { use Logger, Validator; }</pre>
Click to reveal answer
intermediate
What happens if two traits used in a class have methods with the same name?
PHP will give an error unless you resolve the conflict using insteadof or as to choose which method to use or rename one.
Click to reveal answer
Which keyword is used to declare a trait in PHP?
Ainterface
Bclass
Ctrait
Duse
How do you include a trait's methods inside a class?
ABy extending the trait
BBy using the <code>use</code> keyword inside the class
CBy implementing the trait
DBy importing the trait
Can a PHP class use more than one trait?
AYes, by listing traits separated by commas
BNo, only one trait per class
CYes, but only if traits extend each other
DNo, traits cannot be combined
What must you do if two traits used in a class have methods with the same name?
ARename one method or choose which to use with <code>insteadof</code>
BUse <code>extends</code> instead of <code>use</code>
CRemove one trait
DNothing, PHP automatically merges them
Which of these is NOT true about traits?
ATraits can contain methods
BTraits avoid multiple inheritance problems
CTraits help reuse code in multiple classes
DTraits can be instantiated directly
Explain what a trait is and how it helps in PHP programming.
Think about sharing common methods without extending classes.
You got /4 concepts.
    Describe how to resolve method name conflicts when using multiple traits in one class.
    PHP provides special keywords to choose or rename conflicting methods.
    You got /4 concepts.