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?
✗ Incorrect
The
trait keyword declares a trait in PHP.How do you include a trait's methods inside a class?
✗ Incorrect
Inside a class, you include a trait's methods by writing
use TraitName;.Can a PHP class use more than one trait?
✗ Incorrect
A class can use multiple traits by listing them separated by commas in the
use statement.What must you do if two traits used in a class have methods with the same name?
✗ Incorrect
You must resolve method name conflicts using
insteadof or as to rename or select methods.Which of these is NOT true about traits?
✗ Incorrect
Traits cannot be instantiated on their own; they must be used inside classes.
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.