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.

Simple, Beautiful Publishing

This website is powered by Postleaf, an open source blogging platform I built myself. Check it out if you’re looking for a fresh, modern approach to content management.

Author avatar

About the author

Cory LaViska is a founder, web developer, and bootstrapper based in Orlando, Florida. Need to get in touch? You can connect with him on Twitter. Looking for a simple, no-worry CMS for your clients? Try my Surreal CMS!