0

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?

Run
  • 54,938
  • 169
  • 450
  • 748
  • Why not just assign the 'hello' in the constructor for instance then all is set...there is no connection between those two instantiated classes so that the child can inherit the 'hellp' – ka_lin Aug 04 '13 at 18:45
  • sorry, I don't get it. could you please give me an example? thanks. – Run Aug 04 '13 at 18:46
  • awww. ignore it. I got it now. – Run Aug 04 '13 at 18:47
  • my problem is the data must be passed from outside. cannot be set in the parent class. – Run Aug 04 '13 at 18:49

1 Answers1

0

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.

darma
  • 4,687
  • 1
  • 24
  • 25
  • thanks for the reply. how do I `NOT overwrite the __construct method of your child class.`? – Run Aug 04 '13 at 19:00