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
https://forums.phpfreaks.com/topic/231421-dependency-injection/
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

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.