简体   繁体   English

类继承PHP [私有vs保护和公共]

[英]Class inheritance PHP [private vs protected and public]

Example code 1: 示例代码1:

<?php
class People
{
    private function status() {return __METHOD__;}
    public function Sleep(){
        echo $this->status().'<br />';
    }
}
class Programmer extends People
{
    private function status() {return __METHOD__;}
}
$obj = new Programmer();
$obj->Sleep();
?>

Printed: People::status 印刷: People::status

Example code 2: 示例代码2:

<?php
class People
{
    protected function status() {return __METHOD__;}
    public function Sleep(){
        echo $this->status().'<br />';
    }
}
class Programmer extends People
{
    protected function status() {return __METHOD__;}
}
$obj = new Programmer();
$obj->Sleep();
?>

Printed: Programmer::status 印刷: Programmer::status

All different in modifier methods private and protected. 私有和受保护的修饰方法中的所有不同。

Why in first case i get People::status ? 为什么在第一种情况下我得到People::status Why i did not get Programmer::status . 为什么我没有得到Programmer::status

Explain me please, i don't understand this moment. 请解释一下,我不明白这一刻。

Because in the first case the Sleep method still exists only within People part of the object and cannot access Programmer::status because it is private in Programmer part of the object, but it have another method with that name available and not overwritten, the People::status . 因为在第一种情况下, Sleep方法仍然只存在于对象的People部分内,并且不能访问Programmer::status因为它在对象的Programmer部分是private的,但是它有另一个方法,该名称可用且不被覆盖, People::status

In the second case protected allows Programmer::status to overwrite People::status 在第二种情况下, protected允许Programmer::status覆盖People::status

Yes, like this it is possible for two methods of the same name to exist in one object, but each one visible only to methods from the same class definition. 是的,像这样,可以在一个对象中存在两个同名的方法,但每个方法只对同一个类定义中的方法可见。

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

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