I'm trying to re-write my PDO MySQL class, it's using a form of dependency injection.
Here's how it connects:
public function __construct($dsn, $username, $password)
{
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_STATEMENT_CLASS => array("EPDOStatement\EPDOStatement", array($this)),
PDO::ATTR_EMULATE_PREPARES => false, // allows LIMIT placeholders
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
];
parent::__construct($dsn, $username, $password, $options);
}
Then it's called like this:
$dbl = new db_mysql("mysql:host=".$db_conf['host'].";dbname=".$db_conf['database'],$db_conf['username'],$db_conf['password']);
Now, inside another class named "core" it has this in the __construct:
class core
{
public $database;
function __construct($database)
{
$this->database = $database;
}
public static function config($key)
{
if (empty(self::$config))
{
// get config
$get_config = $this->database->select("config", '`data_key`, `data_value`');
$fetch_config = $get_config->fetch_all();
foreach ($fetch_config as $config_set)
{
self::$config[$config_set['data_key']] = $config_set['data_value'];
}
}
// return the requested key with the value in place
return self::$config[$key];
}
}
That's called like so:
$core = new core($dbl);
So it's taking the database connection, and assigning it to $database which is set to "public" inside the core class. The problem is when I call the config function, I get this error:
PHP Fatal error: Uncaught Error: Using $this when not in object context
It mentions the error comes from the line
"$this->database->select" inside the "config"
function.
Your config
method is static.
Static Methods can be accessed without an object being instantiated and so $this
isn't an available handle to the current object.
You can not use $this
in static method, because $this
is reference to class instance, and instance
exists only in objects, you can call static method without creating object, so it can not access class reference..
Try to change your method to be non-static and use it after creating core
class object