Bird
0
0

Given this code, what will be the output?

hard📝 Application Q9 of 15
PHP - Interfaces and Traits
Given this code, what will be the output?
trait T1 {
    public function message() {
        return 'Trait1';
    }
}

trait T2 {
    public function message() {
        return 'Trait2';
    }
}

class MyClass {
    use T1, T2 {
        T2::message insteadof T1;
        T1::message as messageFromT1;
    }
}

$obj = new MyClass();
echo $obj->message() . ' ' . $obj->messageFromT1();
ATrait1 Trait2
BTrait2 Trait1
CTrait1 Trait1
DFatal error: Trait method conflict
Step-by-Step Solution
Solution:
  1. Step 1: Understand trait conflict resolution

    Both traits have message(). The code uses T2::message instead of T1::message, and aliases T1::message as messageFromT1.
  2. Step 2: Determine output of calls

    $obj->message() calls T2's message() returning 'Trait2'. $obj->messageFromT1() calls T1's message() returning 'Trait1'.
  3. Final Answer:

    Trait2 Trait1 -> Option B
  4. Quick Check:

    Trait conflict resolved with insteadof and as [OK]
Quick Trick: Use insteadof and as to resolve trait method conflicts [OK]
Common Mistakes:
  • Expecting fatal error on trait conflict
  • Confusing which trait method is called
  • Forgetting aliasing with 'as'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes