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'
php class Base { private $test; public function __construct(){ require('sub. class. php'); $sub = new Sub; echo($this->getTest()); } public function getTest(){ return $this->test; } protected function setTest($value){ $this->test = $value; } } ?>
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
parent:: is the special name for parent class which when used in a member function.To use the parent to call the parent class constructor to initialize the parent class so that the object inherits the class assignment to give a name. NOTE: PHP does not accept parent as the name of a function.
echo $this->bb;
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 an Airplane
class:
class Airplane { private $pilot; public function __construct( $pilot ) { $this->pilot = $pilot; } }
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:
class Bomber extends Airplane { private $navigator; public function __construct( $pilot, $navigator ) { $this->navigator = $navigator; parent::__construct( $pilot ); // Assigns $pilot to $this->pilot } }
In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With