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';
}
}
First off, Parent is a reserved word. Second off, don’t use
varunless you’re using an older version of PHP. You can use protected. You don’t need to use the parent keyword to access the variable because the child class should inherit it. You can access it via$this->myVarEDIT to clarify
You only need to use
parent::when accessing methods of the base class orstaticvariables of the base class. If you try to access a non static variable of the base class you will get an errorAccess to undeclared static property" fatal error:Here’s an example to get you started.
Here’s a working example of this code.