self:: vs static:: in PHP
self:: vs static:: in PHP is all about inheritance and late static binding. It’s used when you are dealing with overrides and methods coming from the parent class.
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.
class Automobile {
public static $type = "Automobile";
public static function getTypeUsingSelf() {
return self::$type; // bound to Automobile
}
public static function getTypeUsingStatic() {
return static::$type; // late static binding
}
}
class Car extends Automobile {
public static $type = "Car";
}
class Truck extends Automobile {
public static $type = "Truck";
}
class Van extends Automobile {
public static $type = "Van";
}
// ------------------- USAGE -------------------
echo Car::getTypeUsingSelf(); // Output: Automobile
echo "<br>";
echo Car::getTypeUsingStatic(); // Output: Car