Jump to content

Question: Passing and object to another object?


jeboy

Recommended Posts

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?

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

@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.

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.