简体   繁体   中英

Object-oriented php - returning to previous object

Did research, couldn't find answer.

Lets say I have those two classes:

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?
 }
}

Now, let me explain my problem and what I want to do. I can create easily class foo:

$foo = new foo();

And I can use functions over there

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

It uses now functions a and then c. I can put the order next to each other. Lets say I want to create boo and use functions over there too.

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

So, I created boo and use the stuff over there. But lets say now I want to jump back into previous tree without ending the command line and go back with one command, so it will start using foo commands instead?

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

Is it even possible and if yes, how can I accomplish this?

Since PHP 5 constructors must be named __construct() . So in your example the method boo gets never be called and therefore the property $prev will not be set. Change your method boo to __construct and all should be fine.

Edit:

The documentation says that for backward compatibility, it will search for the old-style constructor function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM