【问题标题】:Object-oriented php - returning to previous object面向对象的php - 返回上一个对象
【发布时间】: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()

标签: php oop object


【解决方案1】:

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

编辑:

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

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

【讨论】:

  • 奇怪,即使我确实使用了 __construct,但它似乎仍然不起作用,几乎因为它没有找到 __construct() :/...
  • 好的,它似乎确实有效,而且它不知道如何回到上一个树并建议下一步做什么是日食问题:/...
猜你喜欢
  • 2015-01-15
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2012-09-12
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
相关资源
最近更新 更多