I have a problem. I made a singleton config class but when I have more than one variable to get, it returns 1.
example:
$config = Config::getInstance();
echo $config->get('database.host');
Works fine, returns "localhost".
BUT:
$config = Config::getInstance();
echo $config->get('database.host');
echo $config->get('database.user');
echo $config->get('database.pass');
echo $config->get('database.name');
returns "localhost", 1, 1, 1
Why is that? Here is my config class:
<?php
namespace System\Libraries;
class Config
{
private static $_instance = null;
public function getInstance()
{
if (self::$_instance == null) {
self::$_instance = new Self;
}
return self::$_instance;
}
public function get($path)
{
if (isset($path)) {
$path = explode('.', $path);
$config = require_once 'system/config/config.php';
foreach ($path as $key) {
if (isset($config[$key])) {
$config = $config[$key];
}
}
return $config;
}
}
private function __clone() {}
private function __wakeup() {}
private function __construct() {}
public function __destruct()
{
self::$_instance = null;
}
}
?>
This is expected behavior. require_once
will return true
if the file has been required before. This behavior applies to all *_once functions in PHP, e.g. include_once
. Echoing true
displays 1
(false
would display 0
).
You can fix this by loading the config file initially in the private constructor. This will also speed up your code, because the file doesn't have to be loaded every time you call get()
on your Config class.
class Config
{
/**
* @var Config
*/
private static $_instance = null;
/**
* @var array
*/
private $config;
/**
* Config constructor.
*/
private function __construct()
{
$this->config = require_once('system/config/config.php');
}
/**
* Returns the instance.
*
* @static
* @return \Config
*/
public static function getInstance()
{
if (self::$_instance == null) {
self::$_instance = new Self;
}
return self::$_instance;
}
/**
* Get a config item.
*
* @param $path
*
* @return mixed
*/
public function get($path)
{
if (isset($path)) {
$path = explode('.', $path);
$config = $this->config;
foreach ($path as $key) {
if (isset($config[$key])) {
$config = $config[$key];
}
}
return $config;
}
}
private function __clone() {}
private function __wakeup() {}
public function __destruct()
{
self::$_instance = null;
}
}
Note that the getInstance()
method should be declared static.