简体   繁体   English

子类访问父的私有方法?

[英]child class accessing parent's private method?

A user posted a comment on PHP Visibility manual page . 用户在PHP Visibility手册页上发表了评论。 It's the second most voted comment. 这是第二多被投票的评论。 He used this code example: 他用这个代码示例:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    private function overridden() {
        echo 'base';
    }
}

class child extends base {
    private function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>

Output will be "base". 输出将是“基础”。

As I understand it: the "child" class inherits the inherited() method. 据我所知:“child”类继承了inherited()方法。 Does not inherit the overridden() method since it is private but defines its own one instead. 不继承overridden()方法,因为它是私有的,而是定义自己的方法。 But when the test object (instance of child class) runs the inherited() method it outputs "base". 但是当测试对象(子类的实例)运行inherited()方法时,它输出“base”。

So my questions are: 所以我的问题是:

  1. How come the child runs a method to which it does not have access? 为什么孩子会运行一个它无法访问的方法?
  2. Why it does not run its own redefined method? 为什么它不运行自己的重新定义方法?

Since in the child class you didn't define any function inherited() , it'll have to call its parent's method. 因为在子类中你没有定义任何function inherited() ,所以它必须调用它的父类方法。 As the comment you referenced says: 正如你引用的评论所说:

... private methods are visible only for the class that defines them and the child class does not see the parent's private methods. ...私有方法仅对定义它们的类可见,并且子类不会看到父类的私有方法。 ... ...

That said, since you don't have any public method to reference the child's private method, such as: 也就是说,因为你没有任何公共方法来引用孩子的私有方法,例如:

class child extends base {
    public function inherited() {
        $this->overriden();
    }

    // ...

From my point of view, calling $test->inherited() would use the scope of its parent, so, what happens if you create an instance of the parent class and call $this->inherited() . 从我的角度来看,调用$test->inherited()将使用其父级的范围,因此,如果您创建父类的实例并调用$this->inherited() It'd output base . 它是输出基础

Try doing what i said above: in the child class, copy and paste the parent's inherited method. 尝试做我上面所说的:在子类中,复制并粘贴父的继承方法。 It will output child . 它会输出孩子

I'm not sure this is well explained, if it is, maybe it can help you understand a bit more, if it's not, someone may help me improve it. 我不确定这是否得到了很好的解释,如果是,也许它可以帮助你理解更多,如果不是,有人可以帮助我改进它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM