Reputation: 44992
I have the following 3 classes :
class ParentClass {
protected $myVar = array();
function __construct() {
var_dump($this->myVar);
}
}
class FirstClass extends ParentClass {
protected $myVar = array('defaultVal');
}
class SecondClass extends FirstClass {
protected $myVar = array('anotherVal');
}
If I was to do the following:
$class = new SecondClass();
Then I would get array('anotherVal')
what can I add to the construct of ParentClass so that I would actually get array('defaultVal', 'anotherVal')
Thanks in advance!
Upvotes: 0
Views: 162
Reputation: 44992
After furthur research i found out an easy way to do it get_class_vars:
class ParentClass {
protected $myVar = array();
function __construct() {
$firstClassVars = get_class_vars('FirstClass');
$this->myVar= array_merge($this->myVar, $firstClassVars['myVar']);
var_dump($this->myVar);
}
}
This solves my problems...
Thanks anyway guys!
Upvotes: -1
Reputation: 5266
Using ideas from this page, I would suggest the following:
class ParentClass {
protected $myVar = array();
function __construct() {
var_dump($this->myVar);
}
}
class FirstClass extends ParentClass {
function __construct() {
array_unshift($this->myVar, "defaultVar");
parent::__construct();
}
}
class SecondClass extends FirstClass {
function __construct() {
array_unshift($this->myVar, "anotherVal");
parent::__construct();
}
}
$class = new ParentClass();
$class1 = new FirstClass();
$class2 = new SecondClass();
Which gives me the following output:
array(0) {
}
array(1) {
[0]=>
string(10) "defaultVar"
}
array(2) {
[0]=>
string(10) "defaultVar"
[1]=>
string(10) "anotherVal"
}
Upvotes: 0
Reputation: 4582
For some odd reason, stack overflow keeps erasing my previous answer. So here is the new one.
class ParentClass {
protected $myVar;
function __construct() {
$this->myVar = array();
}
}
class FirstClass extends ParentClass {
function __construct() {
parent::__construct();
$this->myVar[] = 'default val';
}
}
class SecondClass extends FirstClass {
function __construct() {
parent::__construct();
$this->myVar[] = 'another val';
}
public function printArr() {
print_r($this->myVar);
}
}
$class = new Secondclass();
$class->printArr();
Upvotes: 5