抽象方法返回时,PHP成员数据丢失

Here's an example of an abstract class and a derived class. There is one abstract method, "collectData" in class A, that is implemented in class B. When the method "getData" is called, "collectData" is then called, setting values in the private member variable "$data". Afterward, getData returns the contents of this variable. If you run this, you would expect the return value to be array(1, 2, 3). But it is an empty array. Why? I'm using PHP 5.3.10 by the way.

<?php

abstract class A
{
    private $data;

    public function __construct()
    {
        $this->data = array();  
    }

    abstract protected function collectData();

    public function getData()
    {
        $this->collectData();
        return $this->data;
    }
}

class B extends A
{
    protected function collectData()
    {
        $this->data = array(1, 2, 3);
    }
}

$test = new B();
$data = $test->getData();
print_r($data);

It should not be:

private $data;

but:

protected $data;

Private properties are not visible after derivation.

Make the $data property public or protected and You will see...

If the property is private, print_r does not see it... Or call var_dump($data) - this should print out also the private members...

Put a setter and a getter in your abstract class to manage the data property

public function setData($data){
   $this->data = $data;
}

public function getData($data){
   return $this->data;
}