Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php manual visibility example confused

Tags:

visibility

php

I have confused from an example in php manual. It's about visibility. Here is the example.

class Bar {
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }
    public function testPublic() {
        echo "Bar::testPublic\n";
    }
    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}
class Foo extends Bar {
    public function testPublic() {
        echo "Foo::testPublic\n";
    }
    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}
$myFoo = new foo();
$myFoo->test();  
?>

http://www.php.net/manual/en/language.oop5.visibility.php

This example outputs

Bar::testPrivate 
Foo::testPublic

Please can you explain how this happen?

why both testPublic() are not called?

I put a var_dump($this) in Bar class construct. It prints object(Foo)[1]. The thing I know is private properties can be called withing same class.

Then how "Bar::testPrivate" is called?

like image 217
Namal Avatar asked Oct 09 '12 06:10

Namal


1 Answers

Then how "Bar::testPrivate" is called?

When you call $myFoo->test(), it runs the code in the context of Bar because the Foo class didn't override it.

Inside Bar::test(), when $this->testPrivate() gets called, the interpreter will look at Foo first but that method is private (and private methods from descendent classes can't be called from Bar), so it goes one level up until it can find a suitable method; in this case that would be Bar::testPrivate().

In contrast, when $this->testPublic() gets called, the interpreter immediately finds a suitable method in Foo and runs it.

Edit

why both testPublic() are not called?

Only one method gets called when you run $this->testPublic(), the furthest one (in terms of distance to the base class).

If Foo::testPublic() needs to also execute the parent's implementation, you should write parent::testPublic() inside that method.

like image 132
Ja͢ck Avatar answered Sep 28 '22 08:09

Ja͢ck