A Better Way to Write Config Files in PHP

How many times have you seen something like this in a config file?

<?php
$db_host = 'localhost';
$db_name = 'somedb';
$db_user = 'someuser';
$db_pass = 'somepass';
?>

Then, of course, it gets included and the variables are referenced as globals:

<?php
include('config.php');
echo $db_host; // 'localhost'
?>

A Better Way

I'm not a fan of using global variables when they can be avoided, so here's an alternative that gives you much more flexibility with your config files.

<?php
return [
'host' => 'localhost',
'name' => 'somedb',
'user' => 'someuser',
'pass' => 'somepass'
];
?>

Simply returning the array allows you to include it into any variable you choose, which is much nicer than cluttering the global namespace with your config.

<?php
$database = include('config.php');
echo $database['host']; // 'localhost'
?>

Of course, you can return any data you want with this approach — even a multidimensional array.

<?php
return [
'database' => [
'host' => 'localhost',
'name' => 'somedb',
'user' => 'someuser',
'pass' => 'somepass'
],
'other-stuff' => ...
];
?>

This is by far my favorite way to write config files in PHP.

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.