PHP手册OOP可见性示例 - 有人可以解释它

cam*_*kid 6 php oop

我在PHP OOP手册http://www.php.net/manual/en/language.oop5.visibility.php中看到了这个,我无法理解为什么输出不是:Foo :: testPrivate Foo: :testPublic

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(); // Bar::testPrivate 
                // Foo::testPublic
Run Code Online (Sandbox Code Playgroud)

roc*_*est 11

这完全取决于变量/方法的可见性.

你会注意到在Bar课堂上,方法testPrivate()private.这意味着ONLY本身可以访问该方法.没有小孩.

所以当Foo扩展Bar,然后要求运行该test()方法时,它会做两件事:

  1. 它会覆盖该testPublic()方法,因为它是公共的,并且Foo有权使用它自己的版本覆盖它.
  2. 它呼吁test() Bar(因为test()只存在于Bar()).

testPrivate()不是覆盖,是一个包含类的一部分test().因此,Bar::testPrivate印刷.
testPublic() 覆盖,并且是继承类的一部分.因此,Foo::testPublic印刷.