Symfony 7 – PHP – Traits

20 multiple-choice questions about PHP traits: purpose, syntax, conflict resolution (insteadof/as), visibility, properties, constants (8.2), and small code examples.


Question 1: What problem do traits solve in PHP OOP?

Question 2: How do you include a trait inside a class?

Question 3: If a method exists in a class, a trait, and a parent class, which one is used?

Question 4: Two traits define the same method. How do you resolve the conflict?

Question 5: Can you change the visibility of a trait method when using it in a class?

Question 6: Which statement about traits is TRUE?

Question 7: Can traits define properties in PHP?

Question 8: What is the effect of declaring abstract methods inside a trait?

Question 9: Can a trait use other traits?

Question 10: What will this print? trait T{public function hi(){echo "hi";}} class A{use T;} (new A)->hi();

Question 11: Given: trait A{function x(){return "A";}} trait B{function x(){return "B";}} class C{use A,B { A::x insteadof B; B::x as y; }} What does (new C)->x().(new C)->y() return?

Question 12: Which kinds of methods can traits define?

Question 13: Inside a trait, what does self refer to at runtime?

Question 14: Can a trait define __construct, and what if the class already has one?

Question 15: Are constants allowed in traits in PHP 8.2+?

Question 16: What happens if two used traits declare the same property with different definitions?

Question 17: Why do teams often extract cross-cutting behavior into traits?

Question 18: Given trait T{public function run(){}} class A{ use T { run as protected doRun; } } Which calls are valid?

Question 19: Inside a trait, what does static:: call use for binding?

Question 20: If two traits added to a class define the same method and you do not resolve it, what happens?