Static Properties & Late Static Binding

Static Properties & Late Static Binding in PHP: --- On the wall of a factory floor hangs one mechanical tally counter, the kind with a lever that clicks the…


The Analogy: The Factory's Single Wall-Mounted Counter

On the wall of a factory floor hangs one mechanical tally counter, the kind with a lever that clicks the number up by one. It does not belong to any single machine or worker; it belongs to the whole line. Every time a finished unit comes off the belt, whoever is nearest reaches up and clicks it, and the number it shows is the total the line has ever produced. There is exactly one counter. A thousand workers and a thousand machines all read and click the same dial, so the count is shared by everyone and owned by no one in particular.

That wall counter is a static property. Where an ordinary property is a note in each worker's own pocket -- every object carries its own copy -- a static property hangs on the class itself, and every instance shares the one value. Declare public static int $made = 0 and there is a single $made for the entire class, not one per object; any instance that increments it changes the number all the others see. You reach it through the class name, Widget::$made, or inside the class with self::$made, because it is attached to the class rather than to any $this.

Now suppose the company opens a second production line in another hall, a specialised variant of the first. Here the analogy sharpens into the subtlest idea in PHP's object model. When a method on the original line's blueprint says "click the counter", which counter does it mean -- the original hall's, or the one in the hall where this particular machine actually stands? "The counter defined on my own blueprint" is self: it always means the original, fixed when the blueprint was drawn. "The counter in whichever hall I am actually running in" is static: it is decided at runtime by the actual class of the object, even if the method was inherited from a parent. This runtime decision is called late static binding, and static:: is how you ask for it.

The failure mode is using self where you needed static. A factory method on the base blueprint that says return new self() will always build the base model, even when called on a specialised subclass -- the subclass asked for one of itself and got a plain base unit instead, silently the wrong type. Nothing errors; the object is real, just not the class the caller expected, and the mistake surfaces later as a baffling type mismatch far from its cause. self freezes the decision at definition time; static defers it to the actual runtime class. Choosing the wrong one is the single most common static-binding bug, and it is invisible until a subclass exists to expose it.


Syntax or Core Structure

A static property belongs to the class, not to instances, so all objects share one value. A static method is called on the class and has no $this. Both are reached with :: rather than ->.

<?php
declare(strict_types=1);

class Widget {
    public static int $made = 0;

    public function __construct() {
        self::$made++;          // one shared counter for the whole class
    }
}

new Widget();
new Widget();
new Widget();

echo Widget::$made, "\n";

Output:

3

There is a single $made for the Widget class, not one per object. Each construction runs self::$made++, clicking the one shared counter, so after three new Widget() calls the class-level total is 3. It is read as Widget::$made -- through the class name, because the value lives on the class, not on any particular instance. This is the everyday use of static state: a counter, a registry, or a cache that all instances of a class must share.


Technical Depth: self, static, and Late Binding

Four ways to say "this class"

Inside a class you can refer to "the class" in several ways, and they do not all mean the same thing. The table disentangles them.

ReferenceResolves toDecidedSees overrides
self::The class where the code is writtenAt compile timeNo
static::The runtime class of the instanceAt call timeYes
$this::The runtime class of $thisAt call timeYes
parent::The immediate parent classAt compile timeN/A

The pair that matters most is self versus static. self is bound early, at the moment the code is compiled, to the class the code physically lives in. static is bound late -- at the moment of the call -- to the class of the object actually in play. In a base class with no subclasses the two are indistinguishable; the difference only appears once a subclass inherits the method.

The self/static difference made visible

This example puts the two side by side in factory methods, then calls them on both the base and a subclass.

<?php
declare(strict_types=1);

class Base {
    public static function createSelf(): object { return new self(); }
    public static function createStatic(): object { return new static(); }
}

class Derived extends Base {}

echo Base::createSelf()::class, "\n";
echo Base::createStatic()::class, "\n";
echo Derived::createSelf()::class, "\n";
echo Derived::createStatic()::class, "\n";

Output:

Base
Base
Base
Derived

The revealing line is the third: Derived::createSelf() returns a Base, not a Derived, because self inside createSelf was frozen to Base when that method was compiled -- it has no idea it was called via Derived. Only createStatic, using new static(), follows the call through to the runtime class and builds a Derived. This is why factory methods, fluent builders, and any inherited method that must construct or reference "the actual class" use static rather than self. Getting this wrong gives you a base-class object where a subclass was expected, with no error to point at the cause.

Static methods as named constructors

A class with a private constructor plus several public static factory methods gives callers clearly-named ways to build it -- far more readable than one constructor with a mode flag. Because the class is final here, self and static would behave identically, so self is the honest choice.

<?php
declare(strict_types=1);

final class Duration {
    private function __construct(public readonly int $seconds) {}

    public static function fromMinutes(int $m): self { return new self($m * 60); }
    public static function fromHours(int $h): self { return new self($h * 3600); }

    public function __toString(): string { return $this->seconds . 's'; }
}

echo Duration::fromMinutes(2), "\n";
echo Duration::fromHours(1), "\n";

Output:

120s
3600s

The private constructor means the only way to build a Duration is through a named factory, so every call site reads as fromMinutes or fromHours rather than an opaque new Duration(120) whose unit is a guess. Two minutes becomes 120 seconds and one hour becomes 3600. This "named constructor" pattern leans on static methods to make construction expressive, and pairs naturally with readonly for immutable value objects.


Real World Example: Per-Type ID Sequences in a Base Model

A common pattern in a small ORM is a base Model that assigns each new object an auto-incrementing id -- but the sequence must be per type, so users and posts each count from one. This needs both static state (the sequences) and late static binding (to know which subclass is being constructed). The base holds one shared map of table name to counter, and static::table() tells it which counter to bump.

<?php
declare(strict_types=1);

abstract class Model {
    private static array $sequence = [];

    public readonly int $id;

    public function __construct() {
        $table = static::table();                       // late binding: the real subclass
        $next = (self::$sequence[$table] ?? 0) + 1;
        self::$sequence[$table] = $next;
        $this->id = $next;
    }

    abstract public static function table(): string;
}

class User extends Model {
    public static function table(): string { return 'users'; }
}

class Post extends Model {
    public static function table(): string { return 'posts'; }
}

$u1 = new User();
$u2 = new User();
$p1 = new Post();
$u3 = new User();

printf("users: %d %d %d\n", $u1->id, $u2->id, $u3->id);
printf("posts: %d\n", $p1->id);

Output:

users: 1 2 3
posts: 1

The two forms of "static" work together here. self::$sequence is deliberately self, because there must be exactly one shared map for the whole hierarchy -- if it were static each subclass would get its own map and the pattern would collapse. But static::table() is deliberately late-bound, because the base must ask the actual subclass which table it belongs to. So users count 1, 2, 3 and the interleaved post gets its own 1, because each keys into a different slot of the one shared map. It is a compact demonstration of when you want early binding and when you want late binding in the same method.

The pattern is instructive but harbours a serious real-world flaw: the id sequence lives in a static array in process memory, which makes it useless -- and dangerous -- as a real primary-key generator. PHP's shared-nothing model tears down all static state at the end of each request, so the counters reset to zero on the very next web request, and every fresh request would hand out id 1 again, colliding with existing records. Worse, two concurrent requests each keep their own in-memory sequence with no coordination, so both confidently assign the same ids. Real id generation must come from something durable and atomic -- a database auto-increment column or a sequence object -- precisely because it must survive request teardown and serialise across concurrent processes. This example teaches late static binding well, but as an id generator it would corrupt data in production; static process memory is the wrong place for state that must be globally unique and persistent. The safe version keeps the late-static-binding lesson -- static::table() still tells the base which table a subclass maps to -- but delegates id assignment to the database, reading back the value the engine generated (via lastInsertId or a RETURNING clause) rather than inventing one in PHP. That separation is the general rule the example points at: static binding is the right tool for dispatching to the correct subclass behaviour, but any state that must outlive a request or be unique across processes belongs in durable, transactional storage, never in a static property.


Common Mistakes

  1. Using self where you meant static. self freezes to the defining class at compile time, so an inherited factory returns the base type, not the subclass. Use static (new static()) whenever an inherited method must reference the runtime class.
  1. Treating static state as per-instance. A static property is one value shared by every instance of the class. Expecting each object to have its own copy leads to objects trampling each other's data.
  1. Reaching for $this in a static method. Static methods run without an instance, so $this does not exist. Referencing it is a fatal error; use static:: or self:: for class-level members instead.
  1. Forgetting that static state resets each request. In PHP's shared-nothing model, static properties are reinitialised on every request. Relying on them to persist across requests -- as a counter or cache surviving between page loads -- silently fails.
  1. Using static state where injected state belongs. Global static counters and registries are hard to test and reset, and create hidden coupling. Prefer passing collaborators in, reserving static state for genuine class-wide constants and caches.
  1. Making a static property public and mutable. A public static property is a global variable with a namespace. Any code anywhere can rewrite it, reintroducing every problem globals cause. Keep it private and mediate access through methods.
  1. Confusing static:: with the static keyword for local variables. static $x = 0 inside a function is an unrelated feature (a persistent local). static:: in a class is late static binding. Same word, different mechanisms.
  1. Assuming self::method() calls the overridden version. self::foo() calls the version defined in the current class, ignoring a subclass override. If you want the subclass's override, call static::foo().
  1. Sharing one static sequence across subclasses that should be independent. Conversely, using static::$seq when you meant one shared self::$seq gives each subclass its own copy. Decide deliberately whether the state is per-hierarchy or per-subclass.

Best Practices

  • Use static:: for anything an inherited method must resolve to the runtime class -- factory methods, fluent returns, class-name lookups.
  • Reserve self:: for when you deliberately mean the defining class, such as a single hierarchy-wide shared store.
  • Keep static properties private and expose controlled access through methods, so class-wide state cannot be rewritten from anywhere.
  • Remember that static state is per-request in PHP; never use it for data that must persist across requests or coordinate across processes.
  • Prefer dependency injection over static registries for anything you will want to test, mock, or reset between test cases.
  • Use static factory methods (Model::create()) with new static() to build the correct subclass, giving callers a named, discoverable constructor.
  • Limit static state to genuine class-wide concerns -- caches, immutable configuration, counters -- rather than as a convenient global.
  • When both early and late binding appear in one method, comment why each was chosen, since the distinction is easy to misread later.

Practice Exercises

  1. Write a Counter class with a private static total and instance-level increments, exposing Counter::total(). Create several instances and show they all contribute to one shared total.
  1. Build a base class Shape with a static factory make(...$args): static using new static(), subclass it as Circle, and prove Circle::make() returns a Circle, not a Shape.
  1. Demonstrate the reset behaviour: write a script that increments a static counter, and explain in a comment why running the same script as two separate requests would each start from zero.
  1. Extend the model registry so each subclass can also report static::count() -- how many of that specific type have been created -- keeping the underlying map shared via self while the lookup key comes from static::table().