i have these in Database.php
class Database
{
private $dbname = 'auth';
private $db_instance;
public function __construct($q)
{
if(!$this->db_instance)
$this->db_instance = new SQLite3($q);
}
private function init()
{
if(!$this->db_instance)
{
$this->db_instance = new SQLite3($dbname);
}
}
private function close()
{
if($this->db_instance)
$this->db_instance->close();
}
static public function fetch_a_row($q)
{
$this->init();
$res = $this->db_instance->query(SQLite3::escapeString($q));
$ret = $res->fetchArray(SQLITE3_ASSOC);
$this->close();
return $ret;
}
static public function exec($q)
{
$this->init();
$this->db_instance->exec(SQLite3::escapeString($q));
$this->close();
}
}
in try to call him on index.php
<?php
require_once('Database.php');
$ret = Database::fetch_a_row('SELECT * FROM user WHERE uname = "test"');
echo $ret['id'];
?>
but response :
Fatal error: Using $this when not in object context in /www/cgi-bin/auth/Database.php on line 29
is there anyone could help ?
thank in advance
In your static method, you are using the instance accessor
$this->which is not valid syntax. Typically, you would need to useself::, but it isn’t as simple as that. Take a look at this question, it should explain the difference between usingself(when in static methods) and$this(when in non-static methods).From a glance at the code though, the
Databaseclass requires you to instantiate the object in order to create the DB instance utilised later on. For this reason, it would make more sense to make your query methodsfetch_a_rowandexecnon-static, and change your code to instantiate the object and use that instance.However, this is all stuff that you must figure out as the
Databaseclass needs a bit of refactoring in order to work. The first thing to ask yourself would be “why are you utilising static methods?” – if you don’t need them, it may be simpler to use non-statics (as mentioned above). From there, I guess it’s up to you the direction you take.