Back to PHP tutorials
Intermediate17 min read

Object-Oriented PHP

Build maintainable PHP with classes, inheritance, interfaces, traits, and visibility modifiers.

Classes and Objects

Classes define properties and methods; objects are instances created with new. Constructors __construct initialize state. readonly properties (PHP 8.2+) assign once.

Typed properties enforce types on assignment. Nullable and union types document optional fields explicitly.

Encapsulation hides internals—expose behavior through methods rather than public mutable state everywhere.

  • Use constructor property promotion for DTOs
  • Prefer immutability for value objects
  • Implement __toString sparingly with clear semantics
class Order {
    public function __construct(
        public readonly string $id,
        private float $total,
    ) {}

    public function total(): float {
        return $this->total;
    }
}

Inheritance, Interfaces, and Traits

Extend classes with extends; override methods respecting parent signatures with LSP. abstract classes partial implement shared logic.

Interfaces define contracts without implementation. Classes implement multiple interfaces; only one class inheritance allowed.

Traits mix reusable methods into classes resolving duplicate inheritance limitations—avoid trait collision with insteadof and as aliases.

  • Program to interfaces in service containers
  • Keep traits cohesive—do not use as grab bags
  • Document exceptions interfaces may throw
interface Notifier {
    public function send(string $message): void;
}

class EmailNotifier implements Notifier {
    public function send(string $message): void { /* ... */ }
}

Visibility and Magic Methods

public, protected, private control access. protected exposes to subclasses; private hides implementation details.

Magic methods __get, __set, __call enable dynamic behavior—use sparingly as they obscure static analysis.

__invoke makes objects callable; useful for single-action strategy objects passed to higher-order functions.

  • Default to private until subclass access is required
  • Avoid __sleep/__wakeup; use __serialize in PHP 7.4+
  • Implement JsonSerializable for API output types

Get In Touch


Ready to discuss your next project? Drop me a message.