Home > Backend Development > PHP Tutorial > 一个很难理解的PHP继承的问题!

一个很难理解的PHP继承的问题!

WBOY
Release: 2016-06-23 14:02:08
Original
778 people have browsed it

        class B
        {
            public $name ="aaa";
            function fb()
            {
               echo get_class($this),"";
               echo $this->name,"";
            }
        }
        
        class Eb extends  B
        {
            public $name = "xxxxxxxxxxxxxxsylar";
            
            function __construct()
            {
                parent::fb();
            }
        }
   
        
        $eb = new Eb();


//  父类和子类中的$name均声明为public时;执行Eb的构造函数,输出的结果是子类中$name的值xxxxxxxxxxxxxxsylar
//   父类和子类中的$name均声明为private时;执行Eb的构造函数,输出的结果是子类中$name的值aaa

求解?


回复讨论(解决方案)

$name均声明为public时,自然是子类覆盖父类
这一点应该不会有问题吧?
$name均声明为private时,因为方法 fb 是父类的,当然也只能访问父类的私有属性 

你把 fb 方法抄写到 Eb 中,并在 __construct 中加入 $this->fb();
就真相大白了

这个是叫重载
因为是public 子类从父类继承过来变量name 并对其重载,覆盖了原来的值,
private 的时候,子类不能覆盖父类的变量,这时候就只能输出父类自己本来的值了。

1.私有属性不能被覆盖,
2.子类调用父类私有属性 当然直接输出父类的了!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template