Sobes.tech
Middle+

Mis on hilinenud staatiline sidumine PHP-s?

sobes.tech AI

Vastus AI-lt

See this mechanism allows referencing the called class in the context of static calls. It solves the problem related to self-references in inherited classes when using the static:: keyword.

Let's consider an example using self:::

<?php
class A {
    public static function who() {
        echo __CLASS__; // Outputs A
    }
    public static function test() {
        self::who(); // Calls A::who()
    }
}
class B extends A {
    public static function who() {
        echo __CLASS__; // Outputs B
    }
}

B::test(); // Outputs A

In this case, self::who() inside class A will always call the who method from class A, even if test() is called from class B.

Now consider an example with static:::

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Calls `who()` from the class that initiated the `test()` call
    }
}
class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test(); // Outputs B

Here, static::who() inside class A, when called from class B, will refer to class B and call the who() method from class B.

Late static binding allows dynamically determining which class to use in the context of a static call depending on which class was actually called. This is especially useful when working with class hierarchies and static methods that should behave polymorphically. It works by remembering the "called non-rebound class" (the final class in the inheritance chain from which the static call started) and using it for resolving static:: references.