Alex Rivera | Logout

Accessing a parents variable from subclass php and parent keyword?

Asked 2012-06-01T14:21:13.437
8

I have a parent class and a subclass, the parent class has a constructer that sets a var and I would like to use that var in the subclass, I have it working but am getting confused by the keyword parent?

Example

 class Sub extends Parent {
     public function foo() {
         echo $this -> myVar;
     }
 }

 class Parent {
     var $myVar;
     public function __construct() {
          $this -> myVar = 'a';
     }
 }

This worked and I get the value of myVar, but am I supposed to be using the keyword parent and when I do I get an error, example,

 class Sub extends Parent {
     public function foo() {
         echo parent -> myVar;
     }
 }

 class Parent {
     var $myVar;
     public function __construct() {
          $this -> myVar = 'a';
     }
 }
Edit
Report

1 Answer

1

Keyword parent should be used to access methods or static variables of parent class only, so your first code is the proper one, since $myVar is not static.

answered 2012-06-01T14:28:58.340

Your Answer