Jump to content

Dependency injection


c_pattle

Recommended Posts

I'm trying to use dependency injection to pass a database connection to an object but I'm not sure why it's not working.  I have my "dbClass" below that connects to a MySQL database. 

 

class dbClass {
public $db;

function __construct() {
	$this->db = mysql_connect("localhost","username","password") or die ('Could not connect: ' . mysql_error());
	return $this->db;
}
}

 

Then I have my "baseClass".  This is the class that I want to feed to connection too. 

 

class baseClass {
public $mysql_conn;

function __construct($db) {
	$this->mysql_conn = $db;
	$rs = mysql_select_db("webdev_db", $this->mysql_conn) or die ('Could not connect: ' . mysql_error());
}
}

 

And this is my index.php file.  The error I'm getting is "supplied argument is not a valid MySQL-Link resource".  However I tripled checked and my db connection details are definately correct. 

 

$db = new dbClass();
$baseclass = new baseClass($db);

 

Thanks for any help. 

Link to comment
Share on other sites

A) Your return statement in your dbClass constructor doesn't do anything and should be removed.

 

B) Creating an instance of your dbClass in $db means that in the main program $db->db is the connection link.

 

C) When you pass $db into the baseClass() and store it in the $mysql_conn variable, you would access it inside the baseClass() using $this->mysql_con->db

Link to comment
Share on other sites

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.