Search code examples
phpmysqlclasslate-static-binding

Duplicating functions for late static binding


I am trying to get my head around late static binding, and through reading several stack overflow questions and the manual, I am there other than that I don't understand why, in all examples I have found (including the manual), the method that directly echoes the classname is duplicated in the child class.

My understanding is that a class that extends from another inherits all of the methods and properties of it's parent. Therefore, why is the who() method duplicated in the PHP manual example of late static binding. I realise that without it, the parent class is echoed, but cannot understand why.

See code from manual...

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

Why is there the need to rewrite the who() method, and I assume it has to be identical? Thanks in advance.


Solution

  • Late static binding is similar to virtual method call, but it is static.

    In class A, method test call two(). two() must display "A". However because this is similar to virtual method, B::two() is executed instead.

    Here is almost same code, but I believe is more clear what is going on:

    <?php
    class A {
        public static function process() {
            echo "AAAA";
        }
        public static function test() {
            static::process(); // Here comes Late Static Bindings
        }
    }
    
    class B extends A {
        public static function process() {
            echo "BBBB";
        }
    }
    
    B::test();
    

    it prints BBBB when executed.