Late static bindings | static:: usage in a non-static context

124 Views Asked by At

Php manual for the late static bindings states, in the example of static usage in non-static context, that foo() will be copied to B? Is method inheritance copying with scope of the original function being maintained?

<?php
class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

class B extends A {
   /* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class C extends A {
    private function foo() {
        /* original method is replaced; the scope of the new one is C */
    }
}

$b = new B();
$b->test();
$c = new C();
$c->test();   //fails 
1

There are 1 best solutions below

6
On

As far as I can say, this is a problem of scope. When a child class does not override a parent's class method and you call said method via the child class, you will be in the parent class's scope and have access to private methods of the parent class. If you implement a test() method in the child class, you will have that scope when you call it and will not be able to access private methods of the parent class.

I would say that 'copy' is not a fitting term for what's happening because the parent methods are not copied, they are just available in the child class, given the right scope. That is, they don't take the scope of the child class, but keep their own. They are only accessible in the child class if set to protected (or public) or if you call private methods with the parent's scope (as described in your example).

More information from your linke here: Strange behavior when overriding private methods

The official documentation does not explain it explicitly, but I could find this:

Private methods of a parent class are not accessible to a child class. As a result, child classes may reimplement a private method themselves without regard for normal inheritance rules.