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..."

  1. What does it mean "same scope"?
  2. What is the scope of "$this" in the example code?

3 Answers

1
user2864740 On Best Solutions

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's foo - it doesn't matter if $this is an A or B because private 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:

Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the [same] class that defines the member.

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.

0
KAD On

$this is valid at the scope of the class itself, so inside class B calling $this->foo will call foo() function of class B since it is in the scope of B, if you want to call foo() of class A inside class B, you refer to it using the parent keyword :

parent::foo(), in this case foo is not in the local scope of B, it is in the parent scope.

0
Ali On

here is a good read on $this

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

PHP's visibility also can give you some insight about the scope in the class and object level.