What is a key difference between an abstract class and a trait in PHP?
easy📝 Conceptual Q2 of 15
PHP - Interfaces and Traits
What is a key difference between an abstract class and a trait in PHP?
AAn abstract class can be instantiated, but a trait cannot.
BAn abstract class cannot have method implementations, but a trait can.
CA trait cannot have properties, but an abstract class can.
DA trait is used to reuse code in multiple classes, an abstract class is a base class.
Step-by-Step Solution
Solution:
Step 1: Understand traits and abstract classes
Traits are for code reuse across classes; abstract classes serve as base classes with some implemented methods.
Step 2: Analyze the options
Abstract classes can have properties and method implementations and cannot be instantiated directly. Traits can have properties and methods but are not classes.
Final Answer:
A trait is used to reuse code in multiple classes, an abstract class is a base class. -> Option D
Quick Check:
Trait = code reuse, Abstract class = base class [OK]
Quick Trick:Traits reuse code; abstract classes define base behavior [OK]
Common Mistakes:
Believing abstract classes can be instantiated
Assuming traits cannot have properties
Confusing traits with interfaces
Master "Interfaces and Traits" in PHP
9 interactive learning modes - each teaches the same concept differently