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
InvoiceMailerdoesn't calculate totals). - O: extend behavior via new classes, e.g. add a
StripeGatewayimplementingPaymentGateway, without editing callers. - L: subtypes must honour parent contracts. A
ReadOnlyRepositorythat throws onsave()violates it. - I: prefer small interfaces (
Readable,Writable) over one fat one. - D: depend on abstractions; inject
PaymentGatewayrather thannew 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
switchon 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
- 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.