PHP self:: vs static::
20
self:: – Early Binding
Resolves to the class where the method is defined. Overrides in child classes do not affect it.
Example – Methods:
class A {
public static function who() { echo "A"; }
public static function test() { self::who(); }
}
class B extends A {
public static function who() { echo "B"; }
}
B::test(); //Output: A
Example – Properties:
class A {
protected static $value = 'A';
public static function get() { return self::$value; }
}
class B extends A {
protected static $value = 'B';
}
echo B::get(); //Output: A
static:: – Late Static Binding (LSB)
Resolves to the class that made the call, respecting inheritance. Allows polymorphic behavior.
Example – Methods:
class A {
public static function who() { echo "A"; }
public static function test() { static::who(); }
}
class B extends A {
public static function who() { echo "B"; }
}
B::test(); //Output: B
Example – Properties:
class A {
protected static $value = 'A';
public static function get() { return static::$value; }
}
class B extends A {
protected static $value = 'B';
}
echo B::get(); //Output: B
Key Differences
| Feature | self:: | static:: |
|---|---|---|
| Binding | Early | Late |
| Respects overrides | No | Yes |
| Base class | Class where method is defined | Class used to call the method |
Rule of Thumb
- Use
self::when behavior should never change in child classes. - Use
static::for polymorphic behavior (factories, ActiveRecord, extensible classes).