Object-Oriented Programming in PHP

PHP is a language with two faces, and the object-oriented one is the more consequential. It started as a procedural language with a bag of loose procedures and grew a class system that many core developers regard as an afterthought, which is why some of the sharpest edges in the language are still sharp: properties are declared in one place and initialised in another, private means something subtly different from what a Java programmer expects, and a class has no interfaces to implement its own contract. What PHP 8 did was add the pieces that were missing. Typed properties, constructor promotion, readonly state, never returns, enums and named arguments mean that a modern PHP class can state its invariants as clearly as a modern Java class can. By the end of this chapter you will be able to read a PHP class and say what each modifier does, decide where a boundary between two classes belongs, and know which of the language’s several ways of sharing code to reach for.

1. Classes and objects

A class is a description; an object is an instance of it. The description holds state in properties and behaviour in methods.

<?php
class Invoice
{
    private string $customer;
    private float $amount;

    public function __construct(string $customer, float $amount)
    {
        $this->customer = $customer;
        $this->amount = $amount;
    }

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

$invoice = new Invoice('Ada', 100.00);
echo $invoice->total();   // 120

An object is created with new, and the constructor runs at that moment. $this inside a method refers to the current object.

The -> operator reads a property or calls a method. The :: operator is the static one, and it is used for constants, static methods, the parent class and the current class.

2. Properties and visibility

A property declaration has a type, a visibility, and optionally a default value.

<?php
class Config
{
    public string $env = 'production';
    protected int $timeout = 30;
    private array $secrets = [];
}

There are three visibility levels.

VisibilityReachable from
publicEverywhere, including code outside the class
protectedThe class itself and any class that extends it
privateThe class itself only

The detail that surprises Java programmers is that private is not inherited in the usual sense. A child class cannot read a private property of its parent, and doing so produces an “undefined property” warning rather than a compile error.

<?php
class ParentClass
{
    private string $secret = 'hidden';
    protected string $shared = 'visible';
}

class ChildClass extends ParentClass
{
    public function read(): string
    {
        return $this->secret;   // Warning: Undefined property
    }
}

The practical rule is that protected is usually the right choice for a property a subclass genuinely needs, and private is the right choice for everything else.

A typed property that has no default value starts out uninitialized, and reading it before it is assigned is an error rather than null.

<?php
class Box
{
    public int $size;
}

$box = new Box();
echo $box->size;   // Error: Typed property Box::$size must not be accessed before initialization

Giving a typed property a default of null makes it nullable in practice.

<?php
class Box
{
    public ?int $size = null;
}

Readonly properties

A property declared readonly may be written exactly once, and only from inside the scope of the class that declares it. Since PHP 8.1.

<?php
class Point
{
    public function __construct(public readonly int $x, public readonly int $y) {}
}

$p = new Point(1, 2);
echo $p->x;         // 1
$p->x = 5;          // Error: Cannot modify readonly property Point::$x

Readonly is the mechanism that makes a value object safe to share, because nothing can change it after construction. PHP 8.2 extended it to whole classes.

<?php
readonly class Money
{
    public function __construct(public int $amount, public string $currency) {}
}

3. Constructor property promotion

Since PHP 8, a constructor parameter can declare a property directly, which removes the most common boilerplate in the language.

<?php
class Invoice
{
    public function __construct(
        public readonly string $customer,
        public readonly float $amount,
        private string $currency = 'EUR',
    ) {}
}

The promoted properties are declared with exactly the visibility and type written in the parameter list, and they are assigned automatically before the constructor body runs. A promoted property may be readonly, and it may have a default value, but it may not have a type of callable, and it may not be variadic.

The short form above is exactly equivalent to the long form, and the long form is still worth knowing because you will meet it in older code.

<?php
class Invoice
{
    public readonly string $customer;
    public readonly float $amount;

    public function __construct(string $customer, float $amount)
    {
        $this->customer = $customer;
        $this->amount = $amount;
    }
}

4. Constructors and destructors

The constructor is named __construct and runs when the object is created. A class with no constructor is perfectly normal.

The destructor is named __destruct and runs when the object is about to be destroyed, either because the last reference to it goes away or because the script ends.

<?php
class FileHandle
{
    private $handle;

    public function __construct(private string $path)
    {
        $this->handle = fopen($path, 'r');
    }

    public function __destruct()
    {
        if (is_resource($this->handle)) {
            fclose($this->handle);
        }
    }
}

Destructors are a poor substitute for explicit cleanup, because the moment an object is destroyed is not something your program controls. They are also a common source of fatal errors at shutdown, when half the objects in the program have already been destroyed. The modern advice is to close resources explicitly, in a method you call, and to use a destructor only as a last-resort safety net.

5. Magic constants

PHP provides a small set of constants that describe the context the code is running in.

ConstantValue
__CLASS__The name of the class the code is written in
__METHOD__The class name and the method name together
__FUNCTION__The method or function name alone
__DIR__The directory of the file the code is written in
__FILE__The full path of the file the code is written in
__LINE__The line number the constant appears on
__NAMESPACE__The current namespace
<?php
class Report
{
    public function where(): string
    {
        return __CLASS__ . '::' . __METHOD__ . ' in ' . __FILE__ . ':' . __LINE__;
    }
}

__CLASS__ and __METHOD__ are constant expressions, so they can be used in a constant declaration or as a default parameter value.

<?php
class Logger
{
    public const SOURCE = __CLASS__;

    public function write(string $message, string $source = __METHOD__): void
    {
        // ...
    }
}

6. Methods, static, self and parent

A method that does not use $this may be declared static, and a static method belongs to the class rather than to an instance.

<?php
class Money
{
    public static function zero(): self
    {
        return new self(0);
    }

    public function __construct(private int $amount) {}
}

self refers to the class where the code is written. static refers to the class the method was called on, which is late static binding, and it is what allows a base class to return the right subclass.

<?php
class Base
{
    public static function create(): static
    {
        return new static();
    }
}

class Child extends Base {}

echo get_class(Base::create());   // Base
echo get_class(Child::create());  // Child

The difference between self and static is the difference between a fixed decision and a late one, and using static in a factory is almost always what you want.

parent refers to the parent class, and it is how a child method calls the parent implementation.

<?php
class Child extends Base
{
    public function greet(): string
    {
        return 'Child says ' . parent::greet();
    }
}

7. Inheritance and final

A class extends one other class and may implement any number of interfaces.

<?php
class PremiumInvoice extends Invoice implements Payable, Reportable
{
    // ...
}

A class or a method declared final cannot be extended or overridden. It is the way of saying “this is the whole design, do not specialise me”.

<?php
final class Ledger
{
    public function record(string $entry): void
    {
        // ...
    }
}

final on a method has one effect: a child class that declares a method with the same name produces a fatal error.

8. Abstract classes and interfaces

An abstract class cannot be instantiated, and may contain abstract methods that a subclass must implement.

<?php
abstract class Shape
{
    abstract public function area(): float;

    public function describe(): string
    {
        return static::class . ' has area ' . $this->area();
    }
}
<?php
class Square extends Shape
{
    public function __construct(private float $side) {}

    public function area(): float
    {
        return $this->side ** 2;
    }
}

echo (new Square(3))->describe();   // Square has area 9

The describe method is inherited unchanged, and it works for every subclass because area is guaranteed to exist. The abstract class exists precisely to make that guarantee.

An interface states a contract without any implementation.

<?php
interface Payable
{
    public function amount(): float;
    public function pay(): void;
}

An interface may also carry constants.

<?php
interface Payable
{
    public const CURRENCY = 'EUR';

    public function amount(): float;
    public function pay(): void;
}

An interface in PHP may not contain a method body. A shared implementation belongs in an abstract class, or in a trait that the implementing classes opt into.

<?php
abstract class BasePayment implements Payable
{
    public function pay(): void
    {
        // a default implementation that a subclass may override
    }

    abstract public function amount(): float;
}

The choice between an abstract class and an interface is usually about state and reuse. Use an interface when the types share no code and no state but must be interchangeable, and use an abstract class when the subtypes genuinely share an implementation and a common base state.

9. Traits

A trait is a bundle of methods that can be pasted into a class. PHP has no multiple inheritance, and a trait is the answer to “these two unrelated classes need the same three methods”.

<?php
trait Timestamps
{
    public string $createdAt;

    public function touch(): void
    {
        $this->createdAt = date('c');
    }
}

class Post
{
    use Timestamps;
}

A trait may also carry properties, and it may conflict with a method the class already has. Conflicts are resolved with insteadof, and an alias can be kept for the losing version.

<?php
trait A
{
    public function hi(): string { return 'A'; }
}

trait B
{
    public function hi(): string { return 'B'; }
}

class Greeter
{
    use A, B {
        A::hi insteadof B;
        B::hi as hiFromB;
    }
}

A trait is not a type. It cannot be used in a type hint, and an object is not an instance of the trait. Use an interface when you need the type, and a trait when you need the code.

10. Type hints and instanceof

A parameter or a return type may name a class, and the language enforces it.

<?php
function process(Payable $p): float
{
    $p->pay();
    return $p->amount();
}

instanceof tests whether an object is an instance of a class or implements an interface, and it is the runtime check to use when the type is not known statically.

<?php
if ($value instanceof Payable) {
    $value->pay();
}

instanceof also returns false for a class name that does not exist, rather than raising an error, so it is safe to test against a name that may be missing.

11. Exceptions

PHP reports errors in two ways. Some are warnings and notices, which are printed and execution continues. The rest are exceptions, which are thrown as objects and travel up the call stack until they are caught.

<?php
try {
    $result = riskyOperation();
} catch (RuntimeException $e) {
    echo 'Failed: ' . $e->getMessage();
} finally {
    cleanup();
}

The try block is guarded, each catch block names the type it handles, and the finally block runs whether or not an exception was thrown. A finally block is the right place for a cleanup that must happen in both cases.

The exception classes form a small hierarchy. Exception is the base for recoverable problems, and Error is the base for programming errors that the language itself throws, such as a TypeError from a failed type declaration or a DivisionByZeroError from intdiv.

<?php
try {
    intdiv(1, 0);
} catch (DivisionByZeroError $e) {
    echo get_class($e);   // DivisionByZeroError
}

A custom exception extends Exception or one of its more specific children, and it is how a package says something domain-specific went wrong.

<?php
class PaymentFailed extends RuntimeException
{
    public function __construct(
        string $message,
        public readonly string $transactionId,
    ) {
        parent::__construct($message);
    }
}

The catch blocks are tried in order, so the most specific type must come first.

<?php
try {
    charge($order);
} catch (PaymentFailed $e) {
    // the specific case
} catch (RuntimeException $e) {
    // the general case
}

Catching Throwable catches everything, errors included, and it should be reserved for the boundary of the program, such as the top-level request handler.

12. Magic methods

PHP calls a method on your object when a normal operation would otherwise fail or when a special operation needs a hook. These are the magic methods, and they are named with two underscores on both sides.

__toString is called when an object is converted to a string.

<?php
class Money
{
    public function __construct(private int $amount) {}

    public function __toString(): string
    {
        return number_format($this->amount / 100, 2);
    }
}

echo new Money(1234);   // 12.34

__get and __set are called when a property is read or written that is not accessible from the calling scope. They are the basis of a lazy-loading proxy and of a virtual property.

<?php
class Settings
{
    private array $values = ['env' => 'production'];

    public function __get(string $name): mixed
    {
        return $this->values[$name] ?? null;
    }

    public function __set(string $name, mixed $value): void
    {
        $this->values[$name] = $value;
    }
}

__isset and __unset complete the set, so that isset and unset behave consistently with the magic accessors.

__call and __callStatic are called when a method does not exist.

<?php
class Query
{
    public function __call(string $method, array $arguments): mixed
    {
        return "building a query for $method";
    }
}

__invoke makes an object callable, which lets it be used anywhere a callable is accepted.

<?php
class Invokable
{
    public function __invoke(int $value): int
    {
        return $value * 2;
    }
}

$double = new Invokable();
echo $double(21);   // 42

13. Cloning

The clone keyword creates a copy of an object. The copy is shallow: the properties hold the same values, but any property that is itself an object still points at the same object.

<?php
class Order
{
    public array $lines = [];
    public ?Invoice $invoice = null;
}

$original = new Order();
$copy = clone $original;

$copy->lines[] = 'new';
// $original->lines is still empty

__clone is called on the new object after the copy is made, and it is where a deep copy is performed.

<?php
class Order
{
    public array $lines = [];
    public ?Invoice $invoice = null;

    public function __clone(): void
    {
        if ($this->invoice !== null) {
            $this->invoice = clone $this->invoice;
        }
    }
}

14. Serialization

PHP can convert an object to a string and back again with serialize and unserialize.

<?php
class Settings
{
    public string $env = 'production';
}

$serialized = serialize(new Settings());
// O:8:"Settings":1:{s:3:"env";s:10:"production";}

$restored = unserialize($serialized);
echo $restored->env;   // production

The format is an implementation detail and is not portable between languages or reliably between PHP versions. It is fine for a cache, a session and a message queue, and it is not fine for anything that crosses a trust boundary.

Deserializing data that came from an untrusted source lets the attacker instantiate arbitrary classes and run their magic methods. The only safe approach is to unserialize with an allow list of permitted classes.

<?php
$restored = unserialize($payload, ['allowed_classes' => [Settings::class]]);

__serialize and __unserialize let a class control what is written and how it is read back, and __sleep and __wakeup are the older equivalents.

15. Iterators and IteratorAggregate

A class that implements Iterator can be used with foreach directly, by implementing current, key, next, rewind and valid.

<?php
class Range implements Iterator
{
    private int $current;

    public function __construct(private int $start, private int $end)
    {
        $this->current = $start;
    }

    public function current(): int { return $this->current; }
    public function key(): int { return $this->current; }
    public function next(): void { $this->current++; }
    public function rewind(): void { $this->current = $this->start; }
    public function valid(): bool { return $this->current <= $this->end; }
}

IteratorAggregate is the simpler and usually better choice. It requires one method that returns a Traversable, and the class gets the iteration behaviour for free.

<?php
class Collection implements IteratorAggregate, Countable
{
    public function __construct(private array $items) {}

    public function getIterator(): Traversable
    {
        return new ArrayIterator($this->items);
    }

    public function count(): int
    {
        return count($this->items);
    }
}

foreach (new Collection([1, 2, 3]) as $item) {
    echo $item, ' ';
}
echo count(new Collection([1, 2, 3]));   // 3

Two more interfaces complete the set that PHP code expects from a container. ArrayAccess makes an object behave like an array with offsetGet, offsetSet, offsetExists and offsetUnset, and JsonSerializable lets a class control its own JSON representation through jsonSerialize.

16. Common mistakes

MistakeWhat actually happensCorrection
Reading an uninitialised typed propertyFatal error, the property has never been assignedGive it a default or assign it in the constructor
Expecting a child class to read a private propertyWarning, the property is not in scopeUse protected
Using self in a factory methodThe base class is always instantiatedUse static for late static binding
Relying on a destructor to release a resourceThe timing is not under your control, and shutdown may fatalClose the resource explicitly
Catching Throwable everywhereReal bugs are silently converted into handled conditionsCatch the specific type
Putting the catch for a base class before a derived oneThe base class matches first, so the specific handler never runsOrder the catches from specific to general
Using a trait where a type is neededA trait is not a type and cannot appear in a type hintDeclare an interface as well
Assuming clone is a deep copyObjects held as properties are shared with the originalImplement __clone
Deserializing untrusted dataThe attacker can instantiate arbitrary classesPass an allowed_classes list
Serializing a class and reading it back with a different shapeThe restored object has missing or renamed propertiesUse __serialize and __unserialize

The object model is the layer that turns a set of functions into a system with boundaries. The next stage of a PHP project is the framework or library layer built on top of it, where namespaces, autoloading, Composer and the conventions of the standard library decide how those boundaries are arranged on disk.

phpfundamentals

Approach:

The subject of this chapter is the object model, but the skill being taught is choosing the right boundary. PHP offers several ways to relate two types: inheritance, an interface, a trait, and the plain delegation of one object holding another, and each of them answers a different question. Inheritance answers “is a kind of”. An interface answers “can do”. A trait answers “has the same code as”. Delegation answers “works with”. Most badly designed PHP code uses inheritance for all four, and the result is a hierarchy that is hard to extend and impossible to test. The approach here is therefore to make each decision explicit: what state a class owns, who may see it, what it promises, and how it shares code. PHP 8 gives the tools to state those decisions in the declarations themselves, so the exercise is not to invent a convention but to use the ones the language already offers.

Steps:

  1. Write the state as typed properties with a chosen visibility, using private by default and protected only where a subclass genuinely needs the value. Remember that private is not inherited into a child scope, and that an uninitialised typed property is an error rather than null.
  2. Mark state that must not change after construction as readonly, and use a readonly class when the whole object is a value. This is what makes such an object safe to share.
  3. Use constructor property promotion so that a property is declared and assigned in one place, and keep the long form in mind for reading older code.
  4. Treat the destructor as a safety net rather than a cleanup mechanism, and close resources explicitly in a method you call.
  5. Use the magic constants for logging and diagnostics, and remember that __CLASS__ and __METHOD__ are constant expressions that can be used as default values.
  6. Distinguish self from static in every factory, because static is what lets a subclass be created by its parent’s constructor.
  7. Choose between an abstract class and an interface by asking whether the subtypes share state and implementation. Use a trait only to share code between unrelated types, and declare an interface alongside it when the type matters.
  8. Mark a class or a method final when the design is complete and should not be specialised.
  9. Type every parameter and return value that is a class, and use instanceof at the point where the type is not known statically.
  10. Catch the most specific exception type first, order the catch blocks from specific to general, and reserve Throwable for the boundary of the program.
  11. Implement the magic methods that the class genuinely needs, and keep the set small: __toString for a readable representation, __get and __set for a virtual or lazy property, __call for a fluent or dynamic interface, __invoke for a callable object.
  12. Decide explicitly whether a copy should be shallow or deep, implement __clone when it should be deep, and never deserialize data from an untrusted source without an allowed_classes list.
  13. Implement IteratorAggregate rather than Iterator for a container, because it is one method instead of five, and add Countable so that count works on the object.

Answer:

After this chapter, a PHP class can be read as a set of decisions rather than as a set of members.

  • State is held in typed properties with a deliberate visibility: private by default, protected only for a genuine subclass need, and readonly for anything that must not change after construction.
  • The constructor declares and assigns in one place through property promotion, and the class guarantees that every property is initialised before any method runs.
  • Relationships are explicit: extends for “is a kind of”, implements for “can do”, use of a trait for “has the same code as”, and composition for “works with”.
  • Behaviour is written so that the type system can check it: every parameter and return value carries a type, and instanceof handles the cases where the type is not known statically.
  • Failure is modelled with exceptions that extend Exception or Error, caught from the most specific type to the most general, with Throwable reserved for the program boundary.
  • Behaviour that PHP cannot express directly is expressed through a small, deliberate set of magic methods.
  • Copying and persistence are explicit decisions: __clone when a deep copy is needed, and __serialize and __unserialize when the stored form has to be controlled.
  • A container implements IteratorAggregate and Countable so that it behaves like the array it stands for.

A reviewer can now tell, from the declarations alone, what state the class owns, who may see it, what it promises, and how it relates to the other types in the system. That is the point at which a codebase becomes a design rather than a pile of files.

More courses

Recommended courses

Found an issue with this content?

Tell us what could be improved.