0
class A 
{
    private function foo() {
        echo "A class success!\n";
    }

    public function test() {
        echo get_class($this) . PHP_EOL; // C class here
        var_dump($this) . PHP_EOL; // $this is object of C class here
        $this->foo(); // but calling A class method foo here while we have our own foo in C. Why?
    }
}

class C extends A 
{
    private function foo() {
        echo "C class success!";
    }
}

$c = new C();
$c->test();

Output

C
object(C)#1 (0) {
}
A class success!

We override private method foo in C class, but still calling A's foo. Why? $this - is value of the calling object. So we cant override private methods or what am i loosing?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
vladimirB
  • 3
  • 1

1 Answers1

0

Since method overriding work only in dynamic binding therefor it is not possible to override private methods. If you inherit parent class with private methods, then private methods will not be available in child class and therefor, you can't override those methods.

What is happening in your case

  1. You create the child class reference
  2. You call the foo method.
  3. First it will check the foo method inside child class.
  4. Since no private methods are accessible outside the class therefor it will go up to the parent and find the foo method.
  5. If it find then it will execute the function which is happening in our case.

So You can solve this problem by just changing the methods from private to public/protected depending upon the situation then everything will work smoothly.

Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12
  • doesn't need to be public, protected should work fine also. He might not want the method to be publicly available outside of class inheritance. – Martin Oct 03 '21 at 06:57
  • Yes exactly, protected will also work. Since protected are only available inside the child class then it will also work perfect – Muhammad Atif Akram Oct 03 '21 at 06:59