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

← All PHP 8 questions