Bird
0
0

Identify the error in this PHP code:

medium📝 Debug Q6 of 15
PHP - Interfaces and Traits
Identify the error in this PHP code:
trait A {
    public function say() {
        return 'Hello';
    }
}

class B {
    use A;
    public function say() {
        return 'Hi';
    }
}

$b = new B();
echo $b->say();
ANo error; output will be 'Hi'
BFatal error: Trait method conflict
CTrait method cannot be overridden in the class
DSyntax error in trait declaration
Step-by-Step Solution
Solution:
  1. Step 1: Understand method overriding with traits

    Class B uses trait A which has say(). B also defines say(), which overrides trait's method.
  2. Step 2: Determine output of $b->say()

    Since class method overrides trait method, calling say() returns 'Hi'. No error occurs.
  3. Final Answer:

    No error; output will be 'Hi' -> Option A
  4. Quick Check:

    Class method overrides trait method = 'Hi' output [OK]
Quick Trick: Class methods override trait methods if names match [OK]
Common Mistakes:
  • Assuming trait methods cannot be overridden
  • Expecting method conflict errors
  • Confusing trait syntax errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes