0
0
PHPprogramming~5 mins

Multiple trait 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 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?
Aextends TraitOne, TraitTwo;
Buse TraitOne, TraitTwo;
Cinclude TraitOne; include TraitTwo;
Dimport TraitOne, TraitTwo;
What keyword helps resolve method name conflicts between traits?
Ainsteadof
Breplace
Cconflict
Doverride
Can a PHP class use traits and still extend a parent class?
AYes, traits and inheritance can be combined
BNo, traits replace inheritance
COnly one trait can be used with inheritance
DTraits only work with interfaces
What will happen if two traits used in a class have the same method name and no conflict resolution is done?
APHP will merge both methods
BPHP will pick the last trait's method
CPHP will pick the first trait's method
DPHP will throw a fatal error
Which of these is NOT a benefit of using multiple traits?
AAvoids deep inheritance trees
BAllows code reuse from multiple sources
CAutomatically resolves method conflicts
DKeeps code flexible
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.