Jump to content

OOP - Accessing parent/child classes


mrdhood

Recommended Posts

Main Object
(
[Visitor] = Visitor Object
(
	[user_info] => Array
	(
		[username] = user
		[user_id] = 1
	)
)
[Room] = Room Object
(
	[info] = Array(
		[id] = 1
		[name] = Lobby
	)
	[messages] = Messages Object
	(
		[messages] = Array
		(
			[0] = Array()
		)
	)
)
)

Is there a way to get the visitor info within the Messages Object?  I'm building it such as $Main = new Main; $Main->Visitor = new Visitor; $Main->Room = new Room; $Main->Room->Messages = new Messages; so they're not static I know that I can pass the $this var through each but that duplicates the class each time and I'm 99% sure that's bad.

Link to comment
https://forums.phpfreaks.com/topic/246603-oop-accessing-parentchild-classes/
Share on other sites

Objects are not duplicated/copied when passed into functions or assigned to.  They're always passed around by their references.

 

The simplest thing to do would be to have your Main object pass its Visitor to its Room as an argument to whatever method you need to use to access your messages:

 

class Main
{
   private $visitor;
   private $room;

   // constructor, other methods, etc.

   public function sendMessageToVisitor($message)
   {
      $this->room->newMessageToVisitor($this->visitor, $message);
   }
}

class Room
{
   private $message;

   // constructor, other methods, etc.

   public function newMessageToVisitor($visitor, $message)
   {
      // do something with $message, $this-message, and $visitor;
   }
}

 

That said, there's likely a better design you could use, but without knowing what you're actually doing, I can't recommend a better way to approach the problem.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.