Classes and Modern OOP

Classes and Modern OOP in PHP: --- In a commercial bakery there is a steel cookie cutter hanging on a hook.


The Analogy: The Cookie Cutter and the Tray of Cookies

In a commercial bakery there is a steel cookie cutter hanging on a hook. The cutter itself is not a cookie -- you cannot eat it, and there is only one of it. What it defines is a shape: press it into rolled dough and out comes a cookie with exactly that outline, every time. Press it a hundred times and you get a hundred cookies, all the same shape, yet each is a separate object on the tray -- one can be iced pink, another dusted with sugar, a third left plain. The cutter is the template; the cookies are the things that actually exist and carry their own state.

That is precisely the relationship between a class and its objects. The class is the cutter: a definition, written once, describing what shape every object of that kind will have -- which properties it holds and which methods it responds to. An object (an instance) is a single cookie stamped from that cutter: a real thing in memory, with its own copy of the properties. Ten Money objects share the one Money class that defines them, but each carries its own amount and currency, and changing one does not smear onto the others.

The cutter also decides what is exposed and what stays internal. Its outer edge is the public shape everyone sees and handles; but a good cutter has a hidden former inside that presses a maker's mark into the underside, something the design relies on but the customer never touches. A class draws the same line with visibility: public members are the outer edge, the surface other code is meant to use, while private members are the internal former -- essential to how the object works, deliberately sealed away so outside code cannot reach in and deform it. This sealing-off is encapsulation, and it is the entire reason objects are more trustworthy than loose arrays of data.

The failure mode is a cutter whose internal former is left exposed on the outside. If the maker's-mark press sticks out where anyone can shove it, a careless hand bends it, and now every cookie comes out with a broken mark and nobody knows which press did it. In code this is a class that makes its internal state public -- any code anywhere can assign to it, so when the value goes wrong you cannot narrow down the culprit, because the whole program had write access. Worse, once outside code depends on that exposed field you can never safely change how the object stores it. Encapsulation is not bureaucratic tidiness; it is the difference between a bug you can locate and one you cannot.


Syntax or Core Structure

A class groups related data (properties) and behaviour (methods) behind a chosen boundary of visibility. You create an object with new, reach its members with ->, and refer to the current object inside a method as $this.

<?php
declare(strict_types=1);

class Counter {
    private int $n = 0;                     // sealed away from outside code

    public function __construct(
        public readonly string $label       // promoted, set once, then fixed
    ) {}

    public function inc(): void {
        $this->n++;
    }

    public function value(): int {
        return $this->n;
    }
}

$hits = new Counter('hits');
$hits->inc();
$hits->inc();
$hits->inc();

echo "count = {$hits->value()}\n";
echo "label = {$hits->label}\n";

Output:

count = 3
label = hits

The property $n is private, so the only way to change it is through inc() -- outside code cannot write $hits->n = 99. The label is declared right in the constructor signature (constructor property promotion, PHP 8.0) and marked readonly (PHP 8.1), so it is assigned once when the object is built and can never be reassigned. Reading it back with {$hits->label} works because it is public; attempting $hits->label = 'x' afterwards would be a fatal error. That combination -- a private mutable counter reachable only through methods, and a public readonly identity fixed at construction -- is the everyday shape of a well-behaved object.


Technical Depth: Visibility, Promotion, and Object Identity

The three visibility levels

Every property and method carries a visibility keyword that decides who may reach it. The table sets out the three levels and where each is appropriate.

KeywordReachable fromTypical use
publicAnywhereThe object's intended interface: methods and fixed identity
protectedThe class and its subclassesState a subclass legitimately needs, hidden from outside
privateOnly the declaring classInternal machinery no other code should touch

The default instinct should be private, widening to protected or public only when a real need appears. A property starts private; if a subclass turns out to need it, promote it to protected; make it public only when outside code genuinely forms part of the contract. This is far easier than the reverse, because narrowing a public member later breaks every caller that came to depend on it.

Constructor property promotion and value objects

Before PHP 8.0, wiring a constructor argument into a property meant declaring the property, listing the parameter, and assigning one to the other -- three lines of ceremony per field. Promotion collapses all three into the parameter list, and combined with readonly and __toString it makes compact, immutable value objects.

<?php
declare(strict_types=1);

class Money {
    public function __construct(
        private int $cents,
        public readonly string $currency
    ) {}

    public function __toString(): string {
        return sprintf('%s %s', number_format($this->cents / 100, 2), $this->currency);
    }
}

echo new Money(1250, 'USD'), "\n";
echo new Money(305, 'EUR'), "\n";

Output:

12.50 USD
3.05 EUR

The whole class is a handful of lines, yet it is a proper value object: $cents is private so no code can corrupt the amount, $currency is public readonly so it is visible but fixed, and __toString lets the object drop straight into an echo or an interpolated string. The magic method __toString is invoked automatically whenever an object is used where a string is expected -- printing, concatenation, interpolation -- which is why echo new Money(1250, 'USD') yields 12.50 USD (the sprintf format puts the formatted amount first, then the currency) without any explicit format call at the call site.

Identity versus equality, and clone

With scalars there is one notion of sameness; with objects there are two, and confusing them causes subtle bugs. The loose == asks whether two objects are of the same class with equal properties; the strict === asks the sharper question of whether they are literally the same instance -- the same object in memory. And because a variable holds a handle to an object, assigning it copies the handle, not the object; clone is what actually makes a separate copy.

<?php
declare(strict_types=1);

class Point {
    public function __construct(public int $x, public int $y) {}
}

$a = new Point(1, 2);
$b = new Point(1, 2);   // same values, different instance
$c = $a;                // same handle -- not a copy
$d = clone $a;          // a distinct object with equal values

$bool = fn (bool $v): string => $v ? 'true' : 'false';
printf("a == b  : %s\n", $bool($a == $b));
printf("a === b : %s\n", $bool($a === $b));
printf("a === c : %s\n", $bool($a === $c));
printf("a == d  : %s\n", $bool($a == $d));
printf("a === d : %s\n", $bool($a === $d));

Output:

a == b  : true
a === b : false
a === c : true
a == d  : true
a === d : false

$a and $b hold equal contents so == is true, but they are different instances so === is false. $c = $a copied the handle, so $a === $c is true -- they are the one object under two names, and mutating through either is visible through the other. clone produced $d, a genuinely separate object with equal values, so it matches $a under == but not under ===. The practical rule: use === when you mean "the very same object" (identity, as in a registry or cache) and == -- or better, an explicit equals() method -- when you mean "equivalent value".


Real World Example: A Shopping Cart from Two Small Classes

A cart is a natural pair of classes: a LineItem value object that knows its own line total, and a Cart that holds items and sums them. Each class guards its own data, and the cart never has to reach inside a line item to compute anything -- it just asks. This is encapsulation doing real work: the arithmetic lives with the data it depends on.

<?php
declare(strict_types=1);

class LineItem {
    public function __construct(
        public readonly string $sku,
        public readonly int $qty,
        private int $unitCents
    ) {}

    public function lineTotal(): int {
        return $this->qty * $this->unitCents;
    }
}

class Cart {
    /** @var LineItem[] */
    private array $items = [];

    public function add(LineItem $item): void {
        $this->items[] = $item;
    }

    public function total(): int {
        return array_reduce(
            $this->items,
            fn (int $carry, LineItem $i): int => $carry + $i->lineTotal(),
            0
        );
    }

    public function render(): void {
        echo "CART\n";
        echo str_repeat('-', 4), "\n";
        foreach ($this->items as $i) {
            printf("%-6s %3d %9s\n", $i->sku, $i->qty, number_format($i->lineTotal() / 100, 2));
        }
        printf("%-6s %3s %9s\n", 'TOTAL', '', number_format($this->total() / 100, 2));
    }
}

$cart = new Cart();
$cart->add(new LineItem('A-1', 2, 500));
$cart->add(new LineItem('B-2', 1, 1250));
$cart->add(new LineItem('C-3', 3, 300));
$cart->render();

Output:

CART
----
A-1      2     10.00
B-2      1     12.50
C-3      3      9.00
TOTAL          31.50

The Cart computes nothing about pricing itself; it delegates each line's total to the LineItem that owns the unit price, then folds those with array_reduce. Two items at 500 cents give 10.00, one at 1250 gives 12.50, three at 300 give 9.00, and the grand total is 31.50. Because $unitCents is private, nothing outside LineItem can quietly change a price after the fact, and because qty and sku are readonly, a line item is effectively immutable once built. The design reads cleanly and each class has exactly one job.

The example is sound as far as it goes, but it carries a real design flaw that a production cart would have to face: money is modelled as a bare int of cents with no currency attached. Add a LineItem priced in dollars to a cart that later receives one priced in yen and total() will cheerfully add the two integers together, producing a meaningless number with no error at all. The type system is satisfied -- both are int -- so nothing complains. The fix is to make price a Money value object carrying its currency and to reject mixed currencies in add(), which is exactly the kind of invariant a class is supposed to enforce. As written, Cart guards how its items are stored but not the one business rule -- single currency -- that actually matters.


Common Mistakes

  1. Making every property public. Exposing internal state means any code anywhere can write to it, so when a value goes wrong the whole program is a suspect. Default to private and widen only when a real need appears.
  1. Confusing the class with the object. The class is the template and exists once; each new produces a separate object with its own properties. Expecting two objects to share a non-static property is a category error.
  1. Forgetting $this inside methods. Referring to a property as $n instead of $this->n inside a method reads a local variable, not the property, and under strict types often errors. Instance members always go through $this.
  1. Reassigning a readonly property. A readonly property may be set exactly once, during construction. Any later assignment -- even inside the class -- is a fatal error, which surprises people who expect to lazily initialise it.
  1. Returning internal mutable state directly. A getter that returns the private array by reference lets callers mutate it behind the object's back. Return a copy, or an immutable view, if the internal collection must stay under the object's control.
  1. Putting logic in the caller that belongs in the class. Computing a line total in the cart rather than the line item scatters rules that should live with their data. Behaviour belongs with the state it depends on.
  1. Using an associative array where a class belongs. A bare ['sku' => ..., 'qty' => ...] has no guaranteed keys, no types, and no methods, so every consumer must re-validate it. A small class makes the shape and the rules explicit once.
  1. Assuming __toString runs everywhere. It is invoked only in string contexts. Passing the object to something expecting an array or int will not call it; a TypeError results instead, so do not rely on it as a general conversion.
  1. Type-hinting a parameter as the wrong level. Accepting a broad type and then reaching for subclass-only members forces unsafe casts. Hint the narrowest type the method actually needs, so the compiler enforces the requirement.

Best Practices

  • Start every property at private and widen to protected or public only when a concrete need appears; narrowing later breaks callers.
  • Use constructor property promotion to declare and assign fields in one place, keeping the constructor free of mechanical boilerplate.
  • Mark fields readonly when they form the object's fixed identity, so immutability is enforced by the language rather than by convention.
  • Keep behaviour with the data it depends on: a class should answer questions about its own state rather than exposing that state for others to compute over.
  • Give value objects a __toString (or a named formatting method) so they present themselves consistently wherever they are displayed.
  • Type-hint properties, parameters, and return types on every method; the object then fails loudly at its boundary rather than deep inside a caller.
  • Model money, dates, and other domain quantities as small value objects rather than bare scalars, so their invariants live in one place.
  • Keep each class focused on one responsibility; when a class starts to accumulate unrelated methods, that is the signal to split it.

Practice Exercises

  1. Write a Temperature class that stores degrees Celsius in a private property, exposes toFahrenheit(): float, and implements __toString to render like "21.0 C". Construct a few and print them.
  1. Build a BankAccount class with a private integer balance in cents, deposit and withdraw methods that reject invalid amounts, and a balance() getter. Prove that outside code cannot set the balance directly.
  1. Extend the cart example so LineItem takes a Money value object instead of a bare int, and make Cart::add throw when a line item's currency differs from the cart's established currency.
  1. Given an associative array of user data, write a User class with promoted readonly properties and a static factory fromArray(array $data): self that validates the required keys and returns a fully-typed object.