I have been playing around with some php classes just trying to learn really but this one has me scratching my head and after lots of searching on SO and google I can't seem to find anything that covers this problem (maybe I'm not wording the search correctly). The config class before used its own pdo connection so I am looking to make sure its not opening a new connection each time, there is another class not shown here but done in the same way and this seems to work. Here is the error:
Call to a member function query() on a non-object in config.class.php on line 15
The only difference I can see that might be causing this is the config class is running a query within the construct where as my other class does not, is this a problem and if so why?
Have tried a few different things but to be honest I just don't understand.. have only been learning php from online resources. Any reading material on this would be appreciated too.
Have been using this db class: https://github.com/indieteq/PHP-MySQL-PDO-Database-Class
class Config
{
public $db;
private $config;
public function __construct()
{
global $db;
$this->db = $db;
$this->config = array();
$rows = $this->db->query("SELECT * FROM config");
foreach($rows as $row) {
$this->config[$row['setting']] = $row['value'];
}
}
public function __get($setting)
{
return $this->config[$setting];
}
public function __set($setting, $value)
{
$update = $this->db->query("UPDATE config SET value = :value WHERE setting = :setting", array("value"=>$value,"setting"=>$setting));
if($update > 0) {
$this->config[$setting] = $value;
return true;
} else {
return false;
}
}
}
The classes are all called on one file:
require(INCLUDE_PATH . "Db.class.php");
include(INCLUDE_PATH . "languages\\en.php");
include(INCLUDE_PATH . "config.class.php");
$db = new Db();
$config = new Config();
global $db, as it may be causing you a scoping problem. Instead, pass the$dbvariable into theConfig::__construct(). Add a parameter to the constructor and use$config = new Config($db);(that is called "dependency injection") Before that though, dovar_dump($db);after callingnew Db()to ensure that object was created.