To make it easier to control your app, configuration - like your database
username and password - is usually isolated into its own file. Let’s create
a new file called config.php. Open up PHP and create a new associative
array with the databse connection string, the username and the password:
But we expected that: the config file doesn’t echo anything, it just sets
a PHP variable. This file isn’t meant to be a page. Instead, we’re going
to require it from other files and use this $config variable.
Let’s do this in get_pets(). Replace each argument to PDO with a key
from the $config variable:
We we refresh, it still works! Remember that require is a function that
basically copies and pastes the contents of another file into this one. My
editor thinks $config is undefined, but we know better than that!
This change looks safe. I mean, it’s not like we’re using this variable
anywhere inside this file. But when we refresh, things explode! We are
referencing the old $config variable inside get_pets, but that wasn’t
Remember how we can return values from a function? We can do the same from
Try it! It works again. We’re using this file almost like a function: require
it and set its return value to a variable. Most included files won’t have
a return line, but it’s really common for configuration.
So hey, we have a configuration file! The advantage of putting all this stuff
into one spot is that you can quickly find and control all the little values
that make your app tick. This also makes our app easier to share with another
developer. If the database password on their computer is different, they
don’t need to dig deep around in your code to find where you hid that.
We’re starting to get organized!