Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.