Bird
0
0

Given two traits TraitA and TraitB both defining a method greet(), how can a class Welcome use both traits and specify that TraitB::greet() should be used instead of TraitA::greet()?

hard📝 Application Q15 of 15
PHP - Interfaces and Traits
Given two traits TraitA and TraitB both defining a method greet(), how can a class Welcome use both traits and specify that TraitB::greet() should be used instead of TraitA::greet()?
trait TraitA {
    public function greet() {
        echo 'Hello from A';
    }
}

trait TraitB {
    public function greet() {
        echo 'Hello from B';
    }
}

class Welcome {
    use TraitA, TraitB {
        TraitB::greet insteadof TraitA;
    }
}
AThe code correctly uses <code>insteadof</code> to prefer TraitB's greet method
BYou cannot use two traits with same method names in one class
CUse <code>as</code> keyword instead of <code>insteadof</code>
DRename one trait method to avoid conflict
Step-by-Step Solution
Solution:
  1. Step 1: Understand trait conflict resolution

    When two traits have methods with the same name, PHP requires explicit conflict resolution using insteadof.
  2. Step 2: Check the code's conflict resolution

    The code uses TraitB::greet insteadof TraitA; which correctly tells PHP to use TraitB's method.
  3. Final Answer:

    The code correctly uses insteadof to prefer TraitB's greet method -> Option A
  4. Quick Check:

    Use 'insteadof' to resolve trait method conflicts [OK]
Quick Trick: Use 'insteadof' to choose trait method on conflict [OK]
Common Mistakes:
  • Ignoring method conflicts in traits
  • Using 'as' instead of 'insteadof' for conflicts
  • Thinking traits with same method names can't be used

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes