Bird
0
0

Given the following traits and class, what will be the output?

hard📝 Application Q15 of 15
PHP - Interfaces and Traits

Given the following traits and class, what will be the output?

trait T1 {
    public function message() {
        return "Trait T1";
    }
}

trait T2 {
    public function message() {
        return "Trait T2";
    }
}

trait T3 {
    public function message() {
        return "Trait T3";
    }
}

class Multi {
    use T1, T2, T3 {
        T3::message insteadof T1, T2;
        T1::message as messageFromT1;
        T2::message as messageFromT2;
    }
}

$obj = new Multi();
echo $obj->message() . ", " . $obj->messageFromT1() . ", " . $obj->messageFromT2();
ATrait T1, Trait T2, Trait T3
BTrait T3, Trait T1, Trait T2
CTrait T3, Trait T2, Trait T1
DTrait T1, Trait T3, Trait T2
Step-by-Step Solution
Solution:
  1. Step 1: Understand insteadof usage

    The class uses T3::message insteadof T1, T2, so message() calls T3's method.
  2. Step 2: Understand aliasing

    Methods from T1 and T2 are aliased as messageFromT1() and messageFromT2() respectively.
  3. Step 3: Determine output

    Calling $obj->message() returns "Trait T3".
    Calling $obj->messageFromT1() returns "Trait T1".
    Calling $obj->messageFromT2() returns "Trait T2".
    Combined output is "Trait T3, Trait T1, Trait T2".
  4. Final Answer:

    Trait T3, Trait T1, Trait T2 -> Option B
  5. Quick Check:

    insteadof picks T3; aliases expose T1 and T2 [OK]
Quick Trick: Use insteadof to pick method; alias to keep others [OK]
Common Mistakes:
  • Ignoring alias and expecting only T3 output
  • Mixing order of aliased methods
  • Confusing insteadof with alias

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes