php OOP父母对孩子的关系

时间:2010-09-15 21:17:33

标签: php oop parent-child

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);

我希望子类能够编辑基础变量$this->c = 'blabla';

我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:1)

不会是我感到自豪的代码(不同的构造函数签名),但这可以工作(单次使用):

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';
 }
}

如果您经常需要它:

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(){
 }
}

根据实际需要,另一种设计模式可能更适合。

答案 1 :(得分:1)

为什么不覆盖它:

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

否则,如果您需要修改实际的基本属性,请使用Wrikken建议的parent

相关问题