Reputation: 10066
I'm trying to use an existing class which has my DB connection in it to make a call within a new class. Here is my code to do this:
class ajaxHandler {
protected static $db;
function __construct() {
if (!class_exists('Db')) {
include "db_class.php";
$db = new Db();
}
}
function show_contest_details ($contest_id){
echo "The contest id is: ".$contest_id;
$event__conetest_details = $db->select("SELECT * FROM FF_CREATE_EVENT");
} // end of show_contest_details function
}
I am getting the following errors:
Notice: Undefined variable: db in /var/www/ajax_class.php on line 18
Fatal error: Call to a member function select() on a non-object in /var/www/ajax_class.php on line 18
How can I use my DB class within this class?
Upvotes: 0
Views: 46
Reputation: 2500
You've forgotten about self::
:
class ajaxHandler {
protected static $db;
function __construct() {
if (!class_exists('Db')) {
include "db_class.php";
}
self::$db = new Db();
}
function show_contest_details ($contest_id){
echo "The contest id is: ".$contest_id;
$event__conetest_details = self::$db->select("SELECT * FROM FF_CREATE_EVENT");
} // end of show_contest_details function
}
Second thing, it is better to move code creating instance of Db
outside the conditional block. You may accidentally include Db
in other place, and then ajaxHandler
will stop working, and you will not understand easily why.
Upvotes: 2
Reputation: 16688
You use class_exists()
to test whether or not you have created the database. That is not correct. class_exists()
checks if the class has been defined, which is true after PHP has loaded the file, not after it has created the first instatiation of the class. What you need is this:
class ajaxHandler {
protected static $db;
function __construct() {
if (is_null(self::$db)) {
include "db_class.php";
self::$db = new Db();
}
}
}
Upvotes: 1