Dmitriy Kozmenko
Dmitriy Kozmenko

Reputation: 1047

Is good idea to add parent reference or value into child class?

I have class that create a lot of other classes.

Is good idea to use reference instead of variable to create link on parent class?

Can I keep memory use this style or it does not matter?

And is this same (one) class? So if I change value in the parent class, can all other classes see new name?

class item implements Iterator {
  private $name = 'Awesome name';
  private $data = Array();
  function __construct () {
    for ($i=0; $i<10; $i++) {
      $this->data[$i] = new type(&$this);
    }       
  }
  public function rewind() { reset($this->data); }
  public function current() { return current($this->data); }
  ...
}

class type {
  private $parent = false;
  function __construct ($a) {
     $this->parent =&$a;
  }
  function do () {
     echo $this->parent->name . "\n";
  }
}

$i = new item ();

foreach ($i as $t) {
   $t->do();
}

Upvotes: 0

Views: 52

Answers (1)

symcbean
symcbean

Reputation: 48357

Is good idea to use reference instead of variable to create link on parent class?

That you think these are different means you haven't really understood how object oriented programming with PHP. Unless you're still programming in PHP 4, lose the '&'s they're not doing anything in your code.

So if I change value in the parent class, can all other classes see new name?

What happened when you tried it?

Upvotes: 1

Related Questions