Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Accessing Parent Class Variable

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'

like image 294
Kuntau Avatar asked Jun 23 '11 15:06

Kuntau


People also ask

How to Access parent class private Variable in child class in Php?

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; } } ?>

Can parent class access child variables?

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.

What is parent keyword in Php?

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.


1 Answers

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.

like image 152
George Cummins Avatar answered Sep 19 '22 02:09

George Cummins