What is the difference between using "self::method" and "static::method" in PHP code?
When using `self::method` in PHP code, the method called is resolved at compile time based on the class in which it is defined. This means that if the method is overridden in a child class, the parent class's method will still be called. On the other hand, using `static::method` resolves the method at runtime based on the calling class. This allows for late static binding, meaning that if the method is overridden in a child class, the child class's method will be called.
class ParentClass {
public static function test() {
echo "ParentClass";
}
}
class ChildClass extends ParentClass {
public static function test() {
echo "ChildClass";
}
public static function callParentTest() {
self::test(); // Output: ParentClass
static::test(); // Output: ChildClass
}
}
ChildClass::callParentTest();
Keywords
Related Questions
- What are some common methods for handling multiple user selections from a form in PHP and storing them in a database efficiently?
- How important is it for beginners to read the README file provided with PHP scripts before attempting to integrate them into their websites?
- Are there any best practices for setting and managing temporary directories for file uploads in PHP applications?