Recall & Review
beginner
What is a trait in PHP?
A trait is a way to reuse code in PHP classes. It lets you include methods from the trait into a class without using inheritance.Click to reveal answer
beginner
How do you use multiple traits in one PHP class?
You list all traits inside the class using the <code>use</code> keyword separated by commas, like <code>use TraitOne, TraitTwo;</code>.Click to reveal answer
intermediate
What happens if two traits have methods with the same name when used in one class?
PHP will give an error unless you resolve the conflict by choosing which method to use or renaming one method with
insteadof or as keywords.Click to reveal answer
beginner
Show a simple example of a PHP class using two traits.<?php
trait A {
public function sayHello() {
return "Hello from A";
}
}
trait B {
public function sayBye() {
return "Bye from B";
}
}
class MyClass {
use A, B;
}
$obj = new MyClass();
echo $obj->sayHello(); // Outputs: Hello from A
echo $obj->sayBye(); // Outputs: Bye from B
?>Click to reveal answer
intermediate
Why use multiple traits instead of inheritance?
Traits let you add features from many sources without the limits of single inheritance. This helps keep code flexible and avoids deep class trees.Click to reveal answer
How do you include multiple traits in a PHP class?
✗ Incorrect
You use the
use keyword followed by trait names separated by commas inside the class.What keyword helps resolve method name conflicts between traits?
✗ Incorrect
The
insteadof keyword lets you specify which trait's method to use when there is a conflict.Can a PHP class use traits and still extend a parent class?
✗ Incorrect
Traits can be used alongside class inheritance to add reusable methods.
What will happen if two traits used in a class have the same method name and no conflict resolution is done?
✗ Incorrect
PHP throws a fatal error because it cannot decide which method to use without explicit conflict resolution.
Which of these is NOT a benefit of using multiple traits?
✗ Incorrect
Traits do not automatically resolve conflicts; you must handle conflicts manually.
Explain how to use multiple traits in a PHP class and how to handle method name conflicts.
Think about how you tell PHP which trait method to use when two traits have the same method.
You got /3 concepts.
Describe why multiple trait usage is helpful compared to single inheritance in PHP.
Consider how traits let you mix and match features without being limited to one parent class.
You got /3 concepts.