Reputation: 91
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).
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.
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.
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
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
*/
Upvotes: 0
Views: 88
Reputation: 52792
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.
Upvotes: 2