Having the code
class A {
private function foo() {}
public function test() {
$this->foo();
static::foo();
}
}
class B extends A {
private function foo() {}
}
And taking what documentation says "...$this-> will try to call private methods from the same scope..."
- What does it mean "same scope"?
- What is the scope of "$this" in the example code?
The wording 'from the same scope'1 means 'from the same class in which this method is defined'.
In this case
test
is defined in the A class. Thus$this->foo()
is going to call A'sfoo
- it doesn't matter if$this
is an A or B becauseprivate
methods are not polymorphic.Contrast this to
protected
methods which are polymorphic so changing the access modifier changes the behavior; and removes the 'same scope' clause.As to why this is the way it is, consider the role of the modifiers:
This means that
$this->foo()
(from A's test) cannot possibly call B's foo, or it would violate this restriction. Other OOP languages work similarly for the same reason: polymorphism only works the caller is allowed to access the method.See Why are private methods not working with polymorphism? which really is a duplicate, albeit the question is written in terms of the experienced behavior.
1 This 'same scope' wording applies to how the method is resolved, and does not relate to
$this
directly. The lexical scope of$this
, a special variable, would be the current instance method; and the value of$this
is that of the instance upon which the method was invoked.