面向对象返回到上一个对象


Object-oriented returning to previous object

做了研究,找不到答案。

假设我有这两个类:

class foo {
 function create_boo() {
  $boo = new boo($this); // creates boo
  return $boo; // returns boo object
 }
 function a() {
  //Do something complex here in class foo
  return $this;
 }
 function b() {
  //Do something complex here in class foo
  return $this;
 }
 function c() {
  //Do something complex here in class foo
  return $this;
 }
}
class boo {
 private $prev;
 function boo ($prev) { // Constructor
  $this->prev = $prev; //In my theory, this saves the previous object, so I can return to it, but doesnt work.
  //do something
 }
 function a() {
  //Do something complex in class boo
  return $this;
 }
 function b() {
  //Do something complex in class boo
  return $this;
 }
 function c() {
  //Do something complex in class boo
  return $this;
 }
 function return_to_foo() {
  return $this->prev; // should return back to previous object?
 }
}

现在,让我解释一下我的问题和我想做什么。我可以很容易地创建类foo:

$foo = new foo();

我可以使用的功能

$foo->a()->c();

它现在使用函数a,然后使用c。我可以把订单放在一起。比方说,我想创建boo并使用那里的函数。

$foo->create_boo()->b()->c();

所以,我创建了boo并使用了那里的东西。但现在我想在不结束命令行的情况下跳回上一个树,并返回一个命令,所以它将开始使用foo命令?

$foo->create_boo()->b()->c()->return_to_foo(); //Next commands are from foo tree;

这可能吗?如果可能,我该如何做到这一点?

由于PHP 5构造函数必须命名为__construct()。因此,在您的示例中,永远不会调用方法boo,因此不会设置属性$prev。将方法boo更改为__construct,一切都会好起来。

编辑:

文档中说,为了向后兼容,它将搜索旧式的构造函数。

http://php.net/manual/en/language.oop5.decon.php