skip to Main Content

The result of this example is " Class A! ", not " Class B! ", why ?

class A {
    private function foo() {
        echo "Class A ! n";
    }
    public function test() {
        var_dump($this);
        $this->foo();
    }
}
class B extends A {
    public function foo() {
        echo "Class B ! n";
    }
}
$b = new B();
$b->test();
// Outputs: 
// object(B)#1 (0) {}
// Class A ! 

I thought the result is " Class B! "

3

Answers


  1. Private classes cannot be modified in the child class

    change code to this and work:

    class A {
       public function foo() {
          echo "Class A ! n";
       }
       public function test() {
          var_dump($this);
          $this->foo();
       }
    }
    class B extends A {
       public function foo() {
          echo "Class B ! n";
       }
    }
    
    $b = new B();
    $b->test();
    
    Login or Signup to reply.
  2. The reason is because test() function inside class AA calls $this->foo() which means the it’s the function within the class(AA) itself and AA->foo() is a private function . Plus $this is a special variable in PHP that refers to current object. When the classes are inheriting see foo() of class BB and CC access modifiers are public but AA->foo() is private. In order to override a function you need to have the same access modifiers. Since the access modifiers are not the same even though the names are similar AA->foo() not be overridden.

    Login or Signup to reply.
  3. Because foo() is private in class A it is not visible outside that class. Therefore foo() in class B is treated as a different function. foo() in B doesn’t override foo() in A. And since test() is part of A, it uses the function from A with that name.

    class A {
       public function foo() {
          echo "Class A ! n";
       }
       public function test() {
          var_dump($this);
          $this->foo();
       }
    }
    

    If you make both functions public, you get the behaviour you were expecting – demo: https://3v4l.org/8kOCl.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search