Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Late Static Binding

PHP implements a feature called late static bindings, or simply late binding, which can be used to reference the called class in a context of static inheritance.

Before PHP 5.3, the self keyword always referred to the class where it was written, regardless of which child class actually made the call. This made it impossible for a static method inherited by a subclass to refer to that subclass reliably: calling a parent’s static method that used new self(), for example, always instantiated the parent class, even when invoked through a child. Late static binding solves this by introducing the static:: keyword, which resolves at call time, hence “late”, to the class that was actually used to make the call, rather than the class where the method was defined.

The mechanism keeps track of the “called class” as execution moves through the call stack: a static call, an instance method call, or a parent:: / self:: forwarding call all propagate that information, unless it is reset by an explicit ClassName:: call, which starts a new binding scope. The special function get_called_class() returns the same class name that static::class would resolve to.

Late static binding is heavily used to implement patterns such as the Active Record pattern, fluent factory methods, or the Singleton pattern, where a base class needs to instantiate or refer to whichever subclass is actually being used, without hardcoding that subclass’s name.

<?php

    class Elephpant {
        public static function who() {
            echo __CLASS__;
        }
        public static function announce() {
            static::who(); // Here comes Late Static Bindings
        }
    }

    class AfricanElephpant extends Elephpant {
        public static function who() {
            echo __CLASS__;
        }
    }

    AfricanElephpant::announce();

?>

Documentation

See Also