Junior — Middle
How do the keywords self:: and static:: differ in the context of calling methods and properties in PHP?
sobes.tech AI
Answer from AI
In PHP, the keywords self:: and static:: are used to access methods and properties within a class, but they have different semantics:
-
self::refers to the method or property of the class where the code is written, ignoring inheritance. It is a static call tied to the current class. -
static::is late static binding. When called from a subclass,static::refers to the class from which the method was called, taking inheritance into account.
Example:
class A {
public static function who() {
echo "Class A\n";
}
public static function test() {
self::who(); // always calls A::who()
static::who(); // calls the method of the class that called test()
}
}
class B extends A {
public static function who() {
echo "Class B\n";
}
}
B::test();
The output will be:
Class A
Class B
This shows that self:: is tightly bound to class A, while static:: considers inheritance and calls the method of class B.