PHP手册OOP可见性示例-有人可以解释吗 [英] PHP manual OOP visibility example - can someone explain it

查看:52
本文介绍了PHP手册OOP可见性示例-有人可以解释吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw this in the PHP OOP manual http://www.php.net/manual/en/language.oop5.visibility.php and I can't get my head around why the output is not: 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

推荐答案

这全部与变量/方法的可见性有关.

It's all about the visibility of the variables / methods.

您会注意到,在Bar类中,方法testPrivate()private.这意味着只有它自己可以访问该方法.没有孩子.

You'll notice that in the Bar class, the method testPrivate() is private. That means that ONLY itself can access that method. No children.

因此,当Foo扩展Bar,然后要求运行test()方法时,它将执行两件事:

So when Foo extends Bar, and then asks to run the test() method, it does two things:

  1. 它覆盖了testPublic()方法,因为它是公共的,并且Foo有权使用其自己的版本覆盖它.
  2. 它在Bar 上调用test() (因为test()仅在Bar()上存在).
  1. It overrides the testPublic() method because it's public, and Foo has the right to override it with it's own version.
  2. It calls test() on Bar (since test() only exists on Bar()).

testPrivate()覆盖,并且是保存test()的类的一部分.因此,将打印Bar::testPrivate.
testPublic() 覆盖,并且是继承类的一部分.因此,将打印Foo::testPublic.

testPrivate() is not overridden, and is part of the class that holds test(). Therefore, Bar::testPrivate is printed.
testPublic() is overridden, and is part of the inheriting class. Therefore, Foo::testPublic is printed.

这篇关于PHP手册OOP可见性示例-有人可以解释吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆