Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Functions and Classes

Late static binding in PHP

Understand PHP late static binding: how static:: differs from self::, new static, get_called_class(), forwarding calls with parent:: and typical uses.

Inside a class, self:: always means "the class where this code was written". static:: means "the class that was actually used for the call". Resolving static:: at run time instead of at the place the code is written is called late static binding.

It matters with inheritance: a method defined in a parent class can create or refer to the child class that called it. This is how named constructors, singletons and active-record style create() methods work.

PHP
class Model
{
    public static function make(): static
    {
        return new static();   // the class you called make() on
    }
}

Try it

PHP self:: versus static::

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Overridable constants and forwarding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
static::method();
static::CONSTANT;
static::$property;
new static(...$args);
static::class
get_called_class()   // same as static::class inside a class

Return type static (PHP 8.0) says "an instance of the class the method was called on", which is more precise than self.

Usage notes

  • Only for static context and inherited instance methods. In an instance method, static::class equals get_class($this).
  • parent::, self:: and static:: forward the late-static-binding class. ClassName::method() does not: it resets it to ClassName, as the second example shows with Shape::viaParent().
  • new self versus new static. new self always creates the class that contains the code, so subclasses get a parent instance. Use new static for factories that subclasses inherit.
  • Static properties are shared with subclasses unless a subclass redeclares them. In the example, A and Counter share one counter, while B has its own.
  • Constants. static::SIDES finds the subclass override; self::SIDES does not.
  • final constructors and new static. A subclass can change the constructor signature, so new static can fail at run time. Mark the constructor final or keep signatures compatible.
  • Not the same as $this. Static methods have no $this; static:: is how they find their class.