php 手动可见性示例混淆 [英] php manual visibility example confused

查看:31
本文介绍了php 手动可见性示例混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被 php 手册中的一个例子搞糊涂了.这是关于可见性.这是示例.

I have confused from an example in php manual. It's about visibility. Here is the example.

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();  
?>

http://www.php.net/manual/en/language.oop5.visibility.php

这个例子输出

Bar::testPrivate 
Foo::testPublic

请你解释一下这是怎么发生的?

Please can you explain how this happen?

为什么两个 testPublic() 都没有被调用?

why both testPublic() are not called?

我在 Bar 类构造中放置了一个 var_dump($this).它打印 object(Foo)[1].我所知道的是私有属性可以在同一个类中调用.

I put a var_dump($this) in Bar class construct. It prints object(Foo)[1]. The thing I know is private properties can be called withing same class.

Bar::testPrivate"是怎么调用的?

Then how "Bar::testPrivate" is called?

推荐答案

那"Bar::testPrivate"是怎么调用的?

Then how "Bar::testPrivate" is called?

当您调用 $myFoo->test() 时,它会在 Bar 的上下文中运行代码,因为 Foo 类没有不要覆盖它.

When you call $myFoo->test(), it runs the code in the context of Bar because the Foo class didn't override it.

Bar::test()内部,当$this->testPrivate()被调用时,解释器会查看Foo首先,该方法是私有的(并且不能从 Bar 调用来自后代类的私有方法),因此它会向上一级,直到找到合适的方法;在这种情况下,这将是 Bar::testPrivate().

Inside Bar::test(), when $this->testPrivate() gets called, the interpreter will look at Foo first but that method is private (and private methods from descendent classes can't be called from Bar), so it goes one level up until it can find a suitable method; in this case that would be Bar::testPrivate().

相反,当 $this->testPublic() 被调用时,解释器会立即在 Foo 中找到合适的方法并运行它.

In contrast, when $this->testPublic() gets called, the interpreter immediately finds a suitable method in Foo and runs it.

编辑

为什么两个 testPublic() 都没有被调用?

why both testPublic() are not called?

当您运行 $this->testPublic() 时,只有一个方法被调用,最远的一个(就到基类的距离而言).

Only one method gets called when you run $this->testPublic(), the furthest one (in terms of distance to the base class).

如果Foo::testPublic() 还需要执行父类的实现,则应该在该方法中编写parent::testPublic().

If Foo::testPublic() needs to also execute the parent's implementation, you should write parent::testPublic() inside that method.

这篇关于php 手动可见性示例混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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