Middle
What are self and static in PHP and how are they used?
sobes.tech AI
Answer from AI
Self refers to the current class where the code is defined. Static refers to the class that was actually called at runtime.
<?php
class MyClass {
public static function myStaticMethod() {
// Here self:: refers to MyClass
echo self::class . "::myStaticMethod() called\n";
}
public static function delegatedStaticMethod() {
// Here static:: refers to MyClass or the child class that called the method
echo static::class . "::delegatedStaticMethod() called\n";
self::myStaticMethod(); // Calls method from MyClass
}
}
class MyChildClass extends MyClass {
public static function anotherStaticMethod() {
// Here static:: refers to MyChildClass
echo static::class . "::anotherStaticMethod() called\n";
self::myStaticMethod(); // Still calls method from MyClass
}
}
MyClass::myStaticMethod(); // MyClass::myStaticMethod() called
MyClass::delegatedStaticMethod(); // MyClass::delegatedStaticMethod() called, MyClass::myStaticMethod() called
MyChildClass::delegatedStaticMethod(); // MyChildClass::delegatedStaticMethod() called, MyClass::myStaticMethod() called
MyChildClass::anotherStaticMethod(); // MyChildClass::anotherStaticMethod() called, MyClass::myStaticMethod() called
?>
| Keyword | Binding | Used for |
|---|---|---|
self |
Binding at compile time to the current class | Access to static properties, constants, and methods of the current class. |
static |
Late static binding to the class that called the method | Access to static properties, constants, and methods in the context of the calling class (can be a child). |
The main difference is late static binding (static), which allows inheritance to override static behavior, whereas self always refers to the class where the code was defined.