PHP Cute Config Function

This is a small and very cute function for working with the web aplication configuration. The function will read the configuration variables from a file called config.php file, with array of variables. Then these can be accessed via a dot (.) notation. If a variable is not found a NULL will be returned, or an optional default variable.

function config($key, $default = null) {
    static $config = null;
    // Is already read? No=>Read config
    if ($config == null) {
        $config = include __DIR__ . '/config.php';
    $temp = $config;
    $path = explode(".", $key);
    foreach ($path as $key){
        if (isset($temp[$key])) {
            $temp = $temp[$key];
        return $default;

    return $temp;


The config.php file contains all the variables for the web application. The variables are in PHP array.

return [
    'app' => [
        'url' => '',
    'database' => [
        'host' => 'localhost',
        'name' => 'databasename',
        'user' => 'databaseuser',
        'pass' => 'databasepass',

And here is how to use it

$appUrl = config('app.url', 'url not found');

$dbUser = config('database.user', 'user not found');


The configuration file should be ignored, and not place in your source control. For GIT add it in your .gitignore file. This will allow you to have different configurations between your development and production environments.