php继承:子类继承父类中的数据?

Sometimes I get lost and started to doubt whether I am doing right in writing classes in php.

For instance, these are quite basic and simple classes,

class base {

    protected $connection = null;

    /**
     * Set the contructor for receiving data.
     */
    public function __construct($connection)
    {
        $this->connection = $connection;

    }

    public function method()
    {
        print_r(get_object_vars($this));
    }

}

class child extends base{

    public function __construct(){
    }

    public function method()
    {
        print_r(get_object_vars($this));
    }
}

I have the child class extended from the base. And I pass some data/ info into base class. And I want the child class inherited the data/ info that I just passed. For instance,

$base = new base("hello");

$child = new child(); 
$child->method(); 

So I would assume I get Array ( [connection] => hello ) as my answer.

But I get this actually Array ( [connection] => )

So that means I have to pass that piece of data every time into the children classes which extended from the base. otherwise I won't get Array ( [connection] => hello ) as my answer.

Is there a correct way to write the children classes to inherit the passed data from the parent class?

It seems you're mixing up the template (the class) and the objects (instances of a class) somehow.

  • How would instanciating one object of class base with some given initial values have any impact on other objects of class child? Instances of class child WILL NOT dynamically "inherit" some property of an instance of class base.

  • If you want to initialize some protected properties from your base class __construct method, and if you want that to be possible also from your child class without having to re-write the __construct method, then you must NOT overwrite the __construct method of your child class.