class A {
private $aa;
protected $bb = 'parent bb';
function __construct($arg) {
//do something..
}
private function parentmethod($arg2) {
//do something..
}
}
class B extends A {
function __construct($arg) {
parent::__construct($arg);
}
function childfunction() {
echo parent::$bb; //Fatal error: Undefined class constant 'bb'
}
}
$test = new B($some);
$test->childfunction();
Question: How do I display parent variable in child? expected result will echo 'parent bb'
all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the
protected
keyword in your class because it throws a fatal error when used in the child class.as mentioned in php.net
With
parent::$bb;
you try to retrieve the static constant defined with the value of$bb
.Instead, do:
Note: you don't need to call
parent::_construct
if B is the only class that calls it. Simply don't declare __construct in B class.$bb has now become the private member of class B after extending class A where it was protected.
So you access $bb like it's an attribute of class B.
Just echo it since it's inherited
The variable is inherited and is not private, so it is a part of the current object.
Here is additional information in response to your request for more information about using
parent::
:Use
parent::
when you want add extra functionality to a method from the parent class. For example, imagine anAirplane
class:Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:
In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.