I have parent and child classes as follows:
abstract class ParentObj {
private $data;
public function __construct(){
$this->data = array(1,2,3);
var_dump($this->data);
$this->method();
}
public function method(){
echo "ParentObj::method()";
}
}
class ChildObj extends ParentObj {
public function __construct(){
parent::__construct();
var_dump($this->data);
}
public function method(){
echo "ChildObj::method()";
}
}
The expected output:
array(1,2,3)
ChildObj::method()
array(1,2,3)
The actual output:
array(1,2,3)
ParentObj::method()
NULL
The problem is, the child object cannot access the data property and the parent refuses to call the overridden method in the child.
Am I doing something wrong, or does anybody have any ideas?
EDIT: I should clarify that I am instantiating a ChildObj as $child = new ChildObj()
You've declared data
as private, so ChildObj won't be able to access it - you need to make it protected instead:
protected $data;
My PHP (5.2.8) prints ChildObj::method()
- are you running an older version?
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