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.
class Model { public static function make(): static { return new static(); // the class you called make() on } }
Try it
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.
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
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::classequalsget_class($this). parent::,self::andstatic::forward the late-static-binding class.ClassName::method()does not: it resets it toClassName, as the second example shows withShape::viaParent().new selfversusnew static.new selfalways creates the class that contains the code, so subclasses get a parent instance. Usenew staticfor factories that subclasses inherit.- Static properties are shared with subclasses unless a subclass redeclares them. In the example,
AandCountershare one counter, whileBhas its own. - Constants.
static::SIDESfinds the subclass override;self::SIDESdoes not. finalconstructors andnew static. A subclass can change the constructor signature, sonew staticcan fail at run time. Mark the constructorfinalor keep signatures compatible.- Not the same as
$this. Static methods have no$this;static::is how they find their class.