PHP
Late static binding with static::
Learn late static binding with static:: and how it differs from self::.
Late static binding with static::
self:: binds to the class where the code is written. static:: binds to the class actually called at runtime. This is called late static binding.
If you write static::class in a parent class method and call it from a subclass, the result is the subclass name. The same method with self::class always returns the parent class name.
Likewise, new static() creates an instance of the called class; new self() creates an instance of the class where the code is written. This is very useful for factory methods.
LSB example: modelSelf and modelStatic
In a Base class, add two methods: modelSelf() returns self::class, modelStatic() returns static::class. Declare both as public static function.
Add a Derived extends Base subclass. Calling Derived::modelSelf() returns Base (the method was written in Base). But Derived::modelStatic() returns Derived (the called class is Derived).
This behavior is a core technique in factory methods and ORMs; a parent class can know the subclass name.
Exercise LSB example: self::class vs static::class
Define a Base class with two static methods: modelSelf(): string returns self::class; modelStatic(): string returns static::class. Then add an empty class Derived extends Base {} subclass. Write echo Derived::modelSelf() . "\n" and echo Derived::modelStatic() . "\n".
Show example solution
:class, the other returning static::class. Add class Derived extends Base {}. Derived::modelSelf() returns 'Base', Derived::modelStatic() returns 'Derived'.
Example solution:
<?php
// Show the self:: vs static:: difference
class Base {
public static function modelSelf(): string {
return self::class;
}
public static function modelStatic(): string {
return static::class;
}
}
class Derived extends Base {}
echo Derived::modelSelf() . "\n";
echo Derived::modelStatic() . "\n";
Test yourself
-
What is the difference between self:: and static::?
- self:: refers to subclass, static:: to parent
- They are the same, no difference
- static:: only works in static methods
- self:: refers to the written class, static:: to the called class
Show answer
self:: refers to the written class, static:: to the called class — Correct. self:: binds to the written class, static:: to the called class.
-
Late binding with new static()
class Base {
public static function create(): static {
return new ____
}
}
Show answer
class Base {
public static function create(): static {
return new static();
}
}
-
Match the self:: and static:: expressions
- self::class
- Name of the written class
- static::class
- Name of the called class
- new self()
- Instance of the written class
- new static()
- Instance of the called class
Next lesson: static vs instance