late static binding in PHP

2019-03-30 12:48发布

问题:

I am reading the php manual about the LSB feature, I understand how it works in the static context, but I don't quite understand it in the non-static context. The example in the manual is this:

<?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
?>

The output is this:

success!
success!
success!


Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

I do not understand for class B, how a private method in A could be inherited to B? Can anyone walk me through what is going on here? Many thanks!

回答1:

The use of late static binding only changes the method that gets chosen for the call. Once the method is chosen, visibility rules are applied to determine whether or not it may be called.

For B, A::test finds and calls A::foo. The comment in B isn't correct--foo isn't copied to B. Since it's private, it is only callable from other methods in A such as A::test.

C fails because the late static binding mechanism locates the new private method C::foo, but A's methods don't have access to it.

I recommended that you reserve late static binding for static fields and methods to avoid confusion.