开发者

php OOP - related to method visibility

Check below given code. I could not get that how it had called testPrivate() method of Class Bar class. As per my assumption it should call method from Foo class i.e. Foo::testPrivate.

Check the demo here

 <?php
    class Bar 
    {
        public function test() {
            $this->开发者_如何学编程;testPrivate();
            $this->testPublic();
        }

        public function testPublic() {
            echo "Bar::testPublic\n";
        }

        private function testPrivate() {
            echo "<br>Bar::testPrivate\n";
        }
    }

    class Foo extends Bar 
    {
        public function testPublic() {
            echo "<br>Foo::testPublic\n";
        }

        private function testPrivate() {
            echo "<br>Foo::testPrivate\n";
        }
    }

    $myFoo = new foo();
    $myFoo->test(); // Bar::testPrivate 
                    // Foo::testPublic
    ?>


If you want a child class to be able to overload a method defined in a parent class, that method has to be declared as protected -- and not as private.


Here, if you change your testPrivate methods definitions to :

protected function testPrivate() {
    echo "<br>Bar::testPrivate\n";
}

and :

protected function testPrivate() {
    echo "<br>Foo::testPrivate\n";
}

You'll get the output you expected :

Foo::testPrivate
Foo::testPublic 


For more informations, you should take a look at the Visibility section of the manual -- quoting the first sentences :

Class members declared public can be accessed everywhere.
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 class that defines the member.


I think you misunderstand what a private method is. Foo::testPrivate() can only be call from inside Foo itself. You can acheive the behaviour you describe with a protected method. Protected means visible to the class and any classes which extend it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜