Below is my code to connect which works fine without configuration file (.ini file). But if I use configuration file, I'm getting error:
Fatal error: Constant expression contains invalid operations in singletonDB.php on line 13.
But as you can see, the variables $dsn, $user and $pass are not static variables. I'm not understanding why I'm getting static variable related error for non-static variable.
My final goal is to use configuration file as well as keeping only singleton connection to DB.
<?php
$config = parse_ini_file("config.ini");
var_dump($config);
// Singleton to connect db.
class ConnectDb
{
// Hold the class instance.
private static $instance = null;
private $pdo;
private $dsn = $config['dsn_config'];
private $user = $config['user_config'];
private $pass = $config['password_config'];
// The db connection is established in the private constructor.
private function __construct()
{
echo nl2br("Inside constructor");
$this->pdo = new PDO($this->dsn, $this->user, $this->pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance()
{
if (! self::$instance) {
self::$instance = new ConnectDb();
}
return self::$instance;
}
public function getConnection()
{
return $this->pdo;
}
}
And this is my configuration file
;Local
dsn_config = 'mysql:host=127.0.0.1;port=3306;dbname=db_name;';
user_config = 'root';
password_config = 'root';
Thank you.