Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent properties and overridden methods in PHP

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()

like image 702
Austin Hyde Avatar asked Jun 29 '09 13:06

Austin Hyde


1 Answers

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?

like image 167
Greg Avatar answered Sep 28 '22 02:09

Greg