Sobes.tech
Middle+

Tell me about the problem of late static binding in the context of PHP.

sobes.tech AI

Answer from AI

Late static binding in PHP (static) allows referencing the called class in the context of inheritance, which solves the problem of referencing the parent class (self).

The problem arises when self:: is used inside a parent class, which still refers to the parent class when called from a child class. This contradicts the expectation that the reference will be to the current, child class.

Example of using self:: and its behavior:

<?php
class ParentClass {
    public static function who_am_i() {
        return __CLASS__;
    }

    public static function who_called() {
        return self::who_am_i();
    }
}

class ChildClass extends ParentClass {
    public static function who_am_i() {
        return __CLASS__;
    }
}

echo ChildClass::who_called(); // Will output ParentClass
?>

Here, self::who_am_i() inside ParentClass::who_called() continues to refer to ParentClass, even when the method is called through ChildClass.

To solve this problem, static:: is used. This is called late static binding because the binding occurs at runtime, not at compile time.

Example of using static:: to solve the problem:

<?php
class ParentClassCorrected {
    public static function who_am_i() {
        return __CLASS__;
    }

    public static function who_called() {
        return static::who_am_i(); // Using static:: instead of self::
    }
}

class ChildClassCorrected extends ParentClassCorrected {
    public static function who_am_i() {
        return __CLASS__;
    }
}

echo ChildClassCorrected::who_called(); // Will output ChildClassCorrected
?>

Now, static::who_am_i() inside ParentClassCorrected::who_called() refers to ChildClassCorrected when called through ChildClassCorrected.

Thus, late static binding using static:: allows methods in the parent class to correctly refer to methods or properties of the calling class in the inheritance hierarchy.

Tell me about the problem of late static binding in… - sobes.tech