mrdhood Posted September 7, 2011 Share Posted September 7, 2011 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 More sharing options...
KevinM1 Posted September 7, 2011 Share Posted September 7, 2011 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. Link to comment https://forums.phpfreaks.com/topic/246603-oop-accessing-parentchild-classes/#findComment-1266440 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.