PHP:使成员对象替换自己

时间:2012-08-23 11:09:36

标签: php class object replace

好的,这是一个奇怪的,我知道这一点,但我想知道它是否有可能。

目标是使类的成员对象用另一个对象替换自己。

class A
{
  public $object;

  public function __construct()
  {
    $this->object = new B($this); // added reference to A
  }
}

class B
{
  private $caller;    // reference to A
  private $myobject;

  public function __construct($caller)
  {
    $this->myobject = new C();
    $this->caller = $caller;
  }

  public function replace()
  {
    // here goes the topic code...
  }
}

class C
{
  // whatever...
}


$A = new A();
$A->object->replace();
// after calling the "replace" method, $A->object becomes the B's child C instance

我知道这样做

$A->object->replace($A);

和B班

public function replace($class)
{
  $class->object=$this->myobject;
}

将是最简单的方法,但我希望每次都避免这个参考通行证......我也不会问你是否在寻找简单的方法;)

欢迎任何形式的技巧。

谢谢专家。

0 个答案:

没有答案