The Problem
Today I needed to have configuraion variables available across multiple PHP scripts / classes, I didn’t want to pass the array accross files or corrupt the global scope.
The solution
A this simple class that makes configuration varibles available throught out my application. It uses a singleton pattern so I know there is only one version of the config. It also implements all the methods to make it behave like an array and an object ( the Countable, ArrayAccess and InteratorAgregate interfaces to be exact).
The Code
Sample Config File:
<?php $config = array(); $config['my_config_value'] = 'its simple'; /* ... set more configuration variables ... */ return $config; // must return an array ?>
Initializing the class:
<?php /* initailize the class at the beginning of a script */ require_once('./SimpleConfig.php'); SimpleConfig::setFile('./config.php'); ?>
Somewhere else in your application:
<?php $config = SimpleConfig::getInstance(); /* Just to show that its an instance not an array */ if ($config instanceof SimpleConfig) { echo "It's an object <br />\n"; } //if /* Access as an array */ echo $config['my_config_value'] ."<br />\n"; // ouputs: its simple /* Access as object */ echo $config->my_config_value ."<br />\n"; // ouputs: its simple ?>
See it in action: demo
Download the files: simple-php-config-file-using-singleton.zip
Thank you for the inspiration! I just extended the idea a little bit to work on ini-style configuration files.