PHP 8 interview question · Most asked

Explain the SOLID principles with PHP examples.

Summary

SOLID stands for Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion, five guidelines for maintainable OO design.

Longer Answer

  • S: a class has one reason to change (an InvoiceMailer doesn't calculate totals).
  • O: extend behavior via new classes, e.g. add a StripeGateway implementing PaymentGateway, without editing callers.
  • L: subtypes must honour parent contracts. A ReadOnlyRepository that throws on save() violates it.
  • I: prefer small interfaces (Readable, Writable) over one fat one.
  • D: depend on abstractions; inject PaymentGateway rather than new Stripe() inside the service.

Code Example

<?php
interface PaymentGateway { public function charge(Money $amount, string $token): string; }

final class CheckoutService
{
    public function __construct(private PaymentGateway $gateway) {} // DIP

    public function pay(Order $order, string $token): string
    {
        return $this->gateway->charge($order->total(), $token);
    }
}

Key Points

  • Small focused classes
  • Polymorphism over switch on types
  • Honor parent contracts
  • Small interfaces
  • Constructor injection of abstractions

Explanation

What interviewers look for

Concrete examples from real code, not textbook definitions.

Common mistakes

  • Over-abstracting everything with interfaces that have a single implementation forever

More most-asked PHP 8 questions

← All PHP 8 questions