简体   繁体   English

继承的函数无法访问子类的私有变量

[英]Inherited function doesn't access private var of the child class

I need some help. 我需要协助。 This code doesn't mean to do anything I was just trying to learn how these inheriting functions work. 这段代码并不意味着要做任何我只是想学习这些继承函数如何工作的事情。

So both parents and child class have $wheels variable and set to private (It doesn't make sense but I was just playing around with the code). 因此,父母和孩子类都具有$ wheels变量并将其设置为private(这没有意义,但我只是在玩代码)。

A method is used to print the number of wheels of the Instance. 一种方法用于打印实例的轮子数。 This method is not overridden in the child class. 子类中不会重写此方法。 Parent and child objects were created and wheel_details() were invoked using each object. 创建父对象和子对象,并使用每个对象调用wheel_details()。

However, when invoked using the child object, the method doesn't use the child object's private var. 但是,当使用子对象调用时,该方法不使用子对象的私有变量。 Instead it prints the parent object's var. 而是打印父对象的var。

How and why do you think it accesses the parent class's private var instead of its own private var. 您如何以及为什么认为它访问父类的私有变量而不是其自己的私有变量。

Appreciate an insight on this. 对此有深刻的见识。 TIA TIA

class Bicycle {

    private $wheels = 2;


    public function wheel_details(){
        return " It has {$this->wheels} wheels. Invoked by ". get_class($this) ;
    }

}

class Unicycle extends Bicycle {

    private $wheels = 1;

}

$b1 =  new Bicycle;
$b2 =  new Unicycle;


echo "Bicycle1 wheels ". $b1->wheel_details(). " <br />";
echo "Bicycle2 wheels ". $b2->wheel_details(). " <br />";

/*Output
=======
Bicycle1 wheels It has 2 wheels. Invoked by Bicycle 
Bicycle2 wheels It has 2 wheels. Invoked by Unicycle
*/

This is by design: 这是设计使然:

Members declared as private may only be accessed by the class that defines the member. 声明为私有的成员只能由定义该成员的类访问。

If you want to override the value from a child class, use protected instead. 如果要覆盖子类的值,请改用protected

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

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