1

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.

DJC
  • 1,175
  • 1
  • 15
  • 39
  • At a quick glance it looks like it's purely there to show which class's method is firing – scrowler Jul 01 '15 at 20:48
  • remove it and the base class method is called though – DJC Jul 01 '15 at 20:49
  • Yes, because you're extending the class and overriding the method. This is standard PHP OOP behaviour. – scrowler Jul 01 '15 at 20:50
  • but overwriting the method with the exact same method as the parent class - which surely has already been inherited? – DJC Jul 01 '15 at 20:51
  • 1
    They may look identical in content but they are different in implementation. They are different instances as well. This particular example [is not specific to static methods](https://eval.in/390655). – scrowler Jul 01 '15 at 20:54

1 Answers1

3

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.

Nick
  • 9,962
  • 4
  • 42
  • 80
  • OK this is helpful. But a related question then - why does the method with __class__ echoed not echo the class B unless it is essentially overwritten in the child class? – DJC Jul 01 '15 at 20:55
  • not sure if I understand - if you do not override the method in B, it will execute A::two(), no matter if you are using self:: or static:: - this is how static methods works in general - they belong to the class they are "first" implemented – Nick Jul 01 '15 at 20:59