【发布时间】:2014-09-11 20:18:52
【问题描述】:
做了研究,找不到答案。
假设我有这两个类:
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;
有没有可能,如果有,我该如何做到这一点?
【问题讨论】:
-
虽然我意识到你写这个例子很匆忙,但不清楚你想做什么,因此很难提供帮助。
-
$boo将成为方法内部的局部变量,每次调用该方法时都会创建和销毁。如果您希望新的 $boo 对象以某种方式存储在容器对象中,则必须改为$this->boo。 -
@Elven 你能把
new $boo改成new boo有点混乱吗。 -
@Rahil 是的,抱歉。是错字:)。
-
你的代码没问题。你在这里打错了
b()->(c),我想你的意思是b()->c()。