Middle
What is the difference between self and static in PHP?
sobes.tech AI
Answer from AI
self refers to the current class at compile time, while static refers to the class that was called at runtime. This is especially important when working with inheritance and late static binding.
Example with self:
<?php
class ParentClass {
public static function who() {
echo __CLASS__; // Always ParentClass
}
public static function test() {
self::who(); // Always calls ParentClass::who()
}
}
class ChildClass extends ParentClass {
public static function who() {
echo __CLASS__; // ChildClass
}
}
ChildClass::test(); // Will output "ParentClass"
Example with static (late static binding):
<?php
class ParentClassWithStatic {
public static function who() {
echo __CLASS__; // ParentClassWithStatic
}
public static function test() {
static::who(); // Calls who() depending on the class that called test()
}
}
class ChildClassWithStatic extends ParentClassWithStatic {
public static function who() {
echo __CLASS__; // ChildClassWithStatic
}
}
ChildClassWithStatic::test(); // Will output "ChildClassWithStatic"
The difference lies in how the final class, whose method will be called, is determined. self is bound at compile time to the class in which it is written. static defers the determination until runtime, using the class from which the call was made.
Comparison table:
| Feature | self | static (Late static binding) |
|---|---|---|
| Binding time | Compile time | Runtime |
| Class reference | The class where self:: is written |
The class that was called |
| Behavior with inheritance | Does not consider overrides in child classes | Considers overrides in child classes |