Sobes.tech
Junior — Middle

What happens if a subclass calls a method that is not defined in it using self::?

sobes.tech AI

Answer from AI

In PHP, the keyword self:: always refers to the class in which it is written, not to a subclass. If a method is called via self:: in a subclass, and that method is not defined in the subclass itself but is defined in the parent class, PHP will try to find this method in the subclass and will not find it, leading to an error.

Example:

class ParentClass {
    public static function foo() {
        echo "Parent foo";
    }
}

class ChildClass extends ParentClass {
    public static function bar() {
        self::foo(); // Attempt to call foo() via self:: in ChildClass
    }
}

ChildClass::bar(); // Error: Call to undefined method ChildClass::foo()

To call a method from the parent class, you should use parent::foo() or static::foo(), if late static binding is required.