Jump to content

Pass Class Instance Into Other Classes


JustinK101

Recommended Posts

I have a class called DatabaseConnection which already has an instance:

 

$db = new DatabaseConnection();

 

Then I have a bunch of other classes that need to use methods and variables inside of DatabaseConnection. How do I pass the instance $db into my other classes? Do I simply say all my other classes should extend DatabaseConnection without giving an instance to $db?

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/101829-pass-class-instance-into-other-classes/
Share on other sites

Do something like this:

 

<?php

class foo
{
  private $db_obj;
   
  public function register (DatabaseConnection $conn) {
    $this->db_obj = $conn;
  }

  public function do_something()
  {
     $this->db_obj->Query(...); // this will call the Query function from the DatabaseConnection class
  }

}

?>

 

The register function in class foo takes a DatabaseConnection object, and now you can use that object from within the class. 

 

Hey AP81:

 

So my final DatabaseConnection class looks like:

 

require_once("DatabaseConfiguration.php");

class DatabaseConnection {
	private $db_connection;
	private $number_db_queries = 0;

	public function __construct() {
		$this->db_connection = @mysql_connect(DatabaseConfiguration::host, DatabaseConfiguration::username, DatabaseConfiguration::password);

		if(empty($this->db_connection)) {
			trigger_error(mysql_error(), E_USER_ERROR);
		}

		if(!@mysql_select_db(DatabaseConfiguration::database, $this->db_connection)) {
			trigger_error(mysql_error(), E_USER_ERROR);
		}
	}

	public function query($sql) {
		$this->number_db_queries++;
		return (mysql_query($sql, $this->db_connection));	
	}

	public function get_number_db_queries() {
		return ($this->number_db_queries);
	}
}

$db = new DatabaseConnection();

 

You will notice I have a little mysql_query wrapper function query() which basically keeps track of the total number of queries executed. Clearly this class method query() is going to get called from the main page itself, other functions, and other classes. So your saying I have to put this new method register() in every class thats need to call query(). How about other standard functions, do I have to declare $db as global in every function? Inst there a better way of doing this?

Well I was just answering specifically to what you asked:

How do I pass the instance $db into my other classes?

 

If your other classes are going utilise most of the functionality of DatabaseConnection extension class, then your other classes would just extend it.

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.