I have never done any Singleton class before and now I figured that for this DB connection it will be a good idea to make one, but I have no clue why it is not working. I really would appreciate if someone would help me out with this one since I want to learn how OOP works...
Anyway, I fixed it with just updating my PHP to latest version, now $DBH = new static();
works fine, thanks people.
I tried to use $DBH = new static();
isntead of $DBH = new self();
but then I have this error:
Parse error: syntax error, unexpected T_STATIC, expecting T_STRING or T_VARIABLE or '$' in mSingleton.php on line 14
Error:
Fatal error: Cannot instantiate abstract class Singleton in mSingleton.php on line 14
Files: (mSingleton.php)
abstract class Singleton
{
protected $DBH;
public static function getInstance()
{
if ($DBH == null)
{
$DBH = new self();
}
return $DBH;
}
}
(mDBAccess.php)
<?php
//mDBAccess.php
//Removed values ofc
$db_host = "";
$db_name = "";
$db_user = "";
$db_pass = "";
include "mSingleton.php";
class DBAccess extends Singleton
{
protected $DBH;
function __construct()
{
try
{
$this->DBH = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
public static function getDBH()
{
return self::getInstance()->DBH;
}
}
(mLog.php)
<?php
//mLog.php
include "mDBAccess.php";
class Log
{
public static function Add($action)
{
try
{
$DBH = DBAccess::getDBH();
//Getting user IP
$ip = $_SERVER['REMOTE_ADDR'];
//Getting time
$time = date('Y-m-d');
//Preparing our SQL Query
$values = array($ip, $action, $time);
$STH = $DBH->prepare("INSERT INTO log (ip, action, time)
VALUES (?, ?, ?)");
//Excecuting SQL Query
$STH->execute($values);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
}
//testing..
Log::Add("ddd");