PHP self:: vs static::
122
self:: – Early Binding
self:: resolves to the class where the calling method is defined. In an inherited method, a call such as self::who() keeps that scope, so it does not use a child class's override.
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)
static:: uses the called class, so an inherited method can dispatch to an override in a child class. See the PHP manual on late static bindings.
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 |
| Resolves against | Class where the method is defined | Called class |
Rule of Thumb
-
Use
self::when the reference should stay tied to the class where the method is defined. -
Use
static::when you need polymorphic behavior (factories, ActiveRecord, extensible classes).