views:

67

answers:

2
class base{
 public $c = 'c';
 public $sub  = '';
 function __construct(){
    $this->sub = new sub();
 }
}

class sub extends base{
 public $ab = 'abs';
 function __construct(){
  $this->c = 'aas';
  echo 'Test';
 }
}


$a = new base();
print_r($a);

I would like to the sub class to edit the base vars $this->c = 'blabla';

how can i achieve this?

A: 

't wouldn't be code I was proud of (different constructor signatures), but this would work (single use):

class base{
 public $c = 'c';
 public $sub  = '';
 function __construct(){
    $this->sub = new sub($this);
 }
}

class sub extends base{
 public $ab = 'abs';
 function __construct($parent){
  $parent->c = 'aas';
  echo 'Test';
 }
}

If you need it more often:

class base{
 private $parent;
 private $top;
 public $c = 'c';
 public $sub  = '';
 function __construct(base $parent = null, base $top = null){
    $this->parent = $parent;
    $this->top    = $top;
    $this->addSub();
 }
 function addSub(){
    $this->sub    = new sub($this,$this->top ? $this->top : $this);
 }

}

class sub extends base{
 public $ab = 'abs';
 function __construct($parent,$top){
  parent::__construct($parent,$top);
  $this->parent->c = 'aas';
 }
 function foo($bar){
    $this->top->c = $bar;
 }
 //preventing infinite recursion....
 function addSub(){
 }
}

Depending on what the actual needs are, another design pattern is likely more suited.

Wrikken
i would have to do that for every function... which would be a hussle
Val
If you have to do that for every function, probably the 'sub' property isn't actually what you want, and you want proper polymorphism. What is the use case here, what are you trying to solve? (And by the way, you could ofcourse set a `parent` property in the constructor so you have a reference handy at all times)
Wrikken
well base would be, the root obj and i was thinking of expanding it accordingly. but use i would like to use "$this" to refer to the "base" class even if it's on child or grand child.
Val
Well, if you have a tree, and need it like that, injecting a reference to the parent at some point is about the only way.
Wrikken
i am not sure i understand that :) can u give me an example?
Val
+1  A: 

Why not just override it:

class sub extends base
{
    public $ab = 'abs';
    public $c = 'blabla';
}

Otherwise, if you need to modify the actual base property, use parent as Wrikken suggested.

webbiedave