In this example it first searches in B (because static:: resolves to B) and as it does not find it, it now searches in "A" and that is why it succeeds, right? or am I wrong?
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo(); // Why does it execute method of "A" if static:: be resolved to "B"?
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
$b = new B();
$b->test();
OUTPUT:
success! success!
Late static binding allows you to refer to the called object's class instead of the class where the method is defined in. But it doesn't change how the scope is resolved, which means that the property/method visibility rules are obeyed as they would if you used
self. When you usestatic, the name of the class will be resolved using runtime information.For more information read late static bindings on php.net.
In your case when you have this:
It's actually the same as this when called on an instance of
B:Upon execution, PHP will start resolving the scope starting with
Bclass. IfBdoesn't have a method with that name, it will check its parent, and so on. YourBclass doesn't have methodfoo, butAdoes. So when you execute it, PHP will effectively try to execute something like this:Now you can see that both lines are the same. The both call the same private method of
Aclass. Yes, the method isprivatebut it's called from within its own class.