PHP 8 interview question · Most asked
When would you use an interface, an abstract class, or a trait in PHP?
Summary
Use an interface to define a contract, an abstract class to share base state and partial implementation in an is-a hierarchy, and a trait to reuse code horizontally across unrelated classes.
Longer Answer
Interfaces declare methods (and constants, and since 8.4 properties) with no state; a class can implement many. They're the backbone of dependency inversion.
Abstract classes can hold properties, constructors and concrete methods, but a class can extend only one. Use them when subclasses genuinely share identity and behavior (e.g., AbstractController).
Traits copy methods/properties into a class at compile time. They're good for cross-cutting helpers but can hide coupling; they're not types, so you can't type-hint a trait.
Key Points
- Interface = contract, multiple allowed, type-hintable
- Abstract class = shared state + partial implementation, single inheritance
- Trait = compile-time code reuse, not a type
- Prefer composition and interfaces over deep inheritance
Comparison / Tradeoffs
| Interface | Abstract class | Trait | |
|---|---|---|---|
| State | No (8.4: hooked props only) | Yes | Yes |
| Multiple | Yes | No | Yes |
| Type-hintable | Yes | Yes | No |
Explanation
What interviewers look for
Design reasoning (contracts vs code reuse) rather than syntax recall.
Follow-up questions
- How do you resolve conflicting trait methods?
More most-asked PHP 8 questions
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.