php oop visibility:父类中的函数如何调用它自己的私有函数和子类公共函数

Sug*_*san 2 php oop

我不知道如何提出这个问题,这就是为什么标题不是.如果有人可以,请改变它..

它位于方法可见性下的PHP文档http://php.net/manual/en/language.oop5.visibility.php中

<?php

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)

在上面的代码中,如何$myFoo->test()打印Bar::testPrivateFoo::testPublic 我认为它将打印Foo::testPrivateFoo::testPublic

dec*_*eze 5

一个private方法或属性只能从完全相同,它的定义同级别访问.Bar::testPrivate只能从叫Bar,那是什么private意思.相反,Foo::testPrivate只能从Foo类定义中的代码中调用.

既然Bar::testBar,它不能打电话Foo::testPrivate.它可以调用的唯一实现是Bar::testPrivate.public但是,该方法没有这样的限制,并且调用了子类的重写方法.

如果你覆盖了test方法Foo,情况就会逆转:

class Foo extends Bar {
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

现在代码完全在内,Foo并且只能调用Foo::testPrivate.