Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q5 of 15
PHP - Interfaces and Traits
What will be the output of this PHP code?
trait T { public function say() { return "Hello"; } } class B { use T; public function say() { return "World"; } } $obj = new B(); echo $obj->say();
AError: Method conflict
BHello
CWorld
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand method precedence with traits

    If a class defines a method with the same name as a trait method, the class method overrides the trait method.
  2. Step 2: Trace the output

    Class B has say() returning "World", so calling say() on B's object returns "World".
  3. Final Answer:

    World -> Option C
  4. Quick Check:

    Class method overrides trait method = "World" [OK]
Quick Trick: Class methods override trait methods with same name [OK]
Common Mistakes:
  • Expecting trait method to override class method
  • Thinking method conflict causes error
  • Ignoring method precedence rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes