1

我是 php 新手,我正在阅读文档以了解可见性。我对文档中的这个例子有点困惑。当调用 to 时$myFoo->test(),不应该调用Foos $this->testPrivate();。我的意思是不$this应该Foo是对象而不是Bar对象?. 据我所知(我在这里可能错了)Foo将有一种自己的test()方法,该方法继承自Bar并且调用$myFoo->test()将调用 '$this->testPrivate' ,其中$this应该是Foos object myFoo。那么它是如何调用BartestPrivate方法呢?

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
?>
4

1 回答 1

5

test()在 中Bar,并将调用Bar 有权访问的最高级别方法。它可以访问Foo's testPublic(因为它是)所以它可以调用它,但public它没有访问权Foo's testPrivate()(因为它是privateFoo所以它调用它自己的testPrivate()

于 2015-11-29T12:07:14.610 回答