jeboy Posted February 5, 2008 Share Posted February 5, 2008 Is it possible to pass an object to another object? How can I use the object's properties and methods that passed into another object? e.g. $object1 = new ClassName1; $object2 = new ClassName2; $object1->functionName($object2); Quote Link to comment Share on other sites More sharing options...
Aureole Posted February 5, 2008 Share Posted February 5, 2008 This might help, I have a main class, this is a function from within that class: <?php function init_session() { require_once( ROOT_PATH . 'classes/class_session.php' ); $this->session = new session; // Note the following line... $this->session->equinox =& $this; $this->session->check(); } ?> The class is called equinox, however within my session class (which is instantiated inside the equinox class) I can use equinox's methods via $session->equinox... if that makes sense? Quote Link to comment Share on other sites More sharing options...
Cep Posted February 7, 2008 Share Posted February 7, 2008 Yes you can pass an object to an object for example here is a very basic runthrough, <?php //create a database object for mysqli $db = new mysqli($server, $user, $pass, $database); class myClass { private $dbase; public function data() { // Here you are using the object $db methods and properties under your class $dbase property $this->dbase->query("SELECT * FROM table"); /Yada yada more code } } //Here you pass the $db object to the new class object $myobject = new myClass; $myobject->dbase = $db; ?> Quote Link to comment Share on other sites More sharing options...
aschk Posted February 11, 2008 Share Posted February 11, 2008 @jeboy: in answer to your question yes. And i see this happening with helper classes (won't go into detail). Here's an example. <?php /** * User class. * */ class user { private $name; public function setName($name){ $this->name = $name; } public function getName(){ return $this->name; } } /** * Page class. * */ class page { private $user; public function setUser(user $user){ $this->user = $user; } public function showUserInfo(){ echo $this->user->getName(); } } // Initialise objects. $page = new page(); $user = new user(); // Set the user's name. $user->setName("joe"); // Set the page's user. $page->setUser($user); // Show user information. $page->showUserInfo(); // Alter the user information. $user->setName("fred"); // Show user information AGAIN! $page->showUserInfo(); ?> As you can see from the above because i'm passing around the user object, once it's set inside the page class i can alter the attribute (name) and then do showUserInfo() again and it'll output the new name. There's nothing wrong with passing objects around (in PHP5, N.B. DON'T do this in PHP4), and it allows your good flexibility. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.