PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I have an active mysql object that contains my conections etc.. $db->query(my query).
I want to pass this object into a new class so i don't have to create the object again
How would i go about passing it into the new class so it's still active?
class NewClass {
var $db;
function __construct($db) {
$this->db=$db;
}
}
Thoughts?
Thanks,
Last edited by Benjamin on Sun Nov 04, 2012 9:20 pm, edited 1 time in total.
Reason:Added [syntax=php||htm||css||javascript||sql||etc] - Please use [syntax] tags when posting code in the forums! Thanks.
Well, i thought but it get the following error:] PHP Fatal error: Call to a member function query() on a non-object in /content/disk/sites/linuxacademy/a/classes/achievements.class.php on line 15
Now here is the deal $db is what I pass into the following class..
Now i know db is my class because it's what i use throughout the code. When i do var_dump($db); it posts the database name
$achievements = new achievements($db);
$achievements->getPointValue("1");
class Achievements {
var $dbase;
function _construct($db) {
$this->db = $db;
}
function getPointValue($action) {
$sql = $this->db->query("SELECT * FROM points");
while($this->db->fetcharray($sql)) {
echo $row['video'];
}
}
function addPoints($userid, $action) {
//userid is the user id //action is the event that occured will pull from db
}
}
Errors out with that error above. however as you can see i'm passing it in. If i do a var_dump($db) ABOVE the new class instance $ach = new etc.. It dumps the db name so i know it's set.
Again, here is the exact code with the error message. Errors out on $sql = $this->db->query("SELECT * FROM points");
error : Call to a member function query() on a non-object
It is an object with a query() method. In fact in a line of code just above the new achievement instance i use $db->query("select name from users"); and it works just fine.
So i know it has a method 1.) because i use it throughout the other 400 lines of code i ahve 2.) here is a new instance of the db class "inside" the achievements class
class Achievements {
var $db;
function __construct($host,$user,$password,$db) {
$this->db = new MySQL($host,$user,$password,$db);
}
public function achievement($action) {
$sql = $this->db->query("SELECT * FROM points");
echo "did something";
while($this->db->fetcharray($sql)) {
}
return $host;
}
function addPoints($userid, $action) {
//userid is the user id //action is the event that occured will pull from db
}
}