How To Use PHP Late Static Binding
self:: vs static:: in PHP is all about inheritance and late static binding. So what is late static binding. When building a child class there may be a static property that overrides that same static property on the parent. So when extending this class you will potentially need access to the property on both classes. The way to do this is through late static binding. You can use the self:: and static:: operators to accomplish this.
self::
- Refers to the class where the method is defined.
- Does not consider inheritance overrides.
static::
- Refers to the class that is actually called at runtime.
- This is called late static binding.
- Allows child classes to override static properties/methods and still be respected.
Example: self:: vs static::
class Animal {
public static $type = "Generic Animal";
public static function getTypeUsingSelf() {
return self::$type; // bound to Animal
}
public static function getTypeUsingStatic() {
return static::$type; // late static binding
}
}
class Dog extends Animal {
public static $type = "Dog";
}
// ------------------- USAGE -------------------
echo Dog::getTypeUsingSelf(); // Output: Generic Animal
echo "<br>";
echo Dog::getTypeUsingStatic(); // Output: Dog