views:

1100

answers:

2

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

+2  A: 

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?

Greg
I'm using PHP 5.2.5
Austin Hyde
A: 

Ok, the problem was the methods were actually declared private, not public as in my post, thus suffering the same symptom as the $data property.

Austin Hyde
edit your question with your answer...
Casey