c_pattle Posted March 22, 2011 Share Posted March 22, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/231421-dependency-injection/ Share on other sites More sharing options...
PFMaBiSmAd Posted March 22, 2011 Share Posted March 22, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/231421-dependency-injection/#findComment-1191014 Share on other sites More sharing options...
c_pattle Posted March 22, 2011 Author Share Posted March 22, 2011 Ah right, I understand it now. Thanks for your help. Quote Link to comment https://forums.phpfreaks.com/topic/231421-dependency-injection/#findComment-1191019 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.