Is there any possibility to create a configuration file with global variables that are visible inside the class? Something similar to this:
config.php:
$config['host_address'] = 'localhost';
$config['username '] = 'root';
$config['password'] = 'root';
$config['name'] = 'data';
db.php:
include('config.php');
class DB
{
private $_config = array($config['host_address'], $config['username'], $config['password'], $config['name']);
...
Current property:
private $ _config = array();
I don't want to transmit through the constructor to my Singleton database connector:
DB::getInstance(array('localhost', 'root', 'root', 'data'));
Everyone has their own preferences. I prefer to store my DB settings in a .ini outside of the webroot and then give it a 0600 chmod value, to prevent anyone but the owner reading it.
An example .ini will look like:
Then you can use the php function
parse_ini_file
then in your constructor you just read that in and parse it into an array:And viola, you have a simple and secure way to setup your database connection. This class was taken from a PDO extender class, so if you are not using PDO you need to change that line, but as yo ucan see you get the username etc in a
$settings
array.I would HIGHLY avoid storing any type of database information into a
CONSTANT
orGLOBAL
type variable. This way, the$settings
is only available to that class function and nothing else, providing an extra bit of security layer.You could try defines:
`Usage:
Your problem is that you are trying to use an expression in the class definition here:
That is syntactically incorrect (you can only use constant values for that), and I wouldn't expect it to locate the intended scope there. What you should do instead is initialize this property in the construtor instead:
Or even lazier, just use
include('config.php');
in place of theglobal $config
alias. That way your config script will extract $config as local variable within the constructor, which is all you need.