Including or requiring files in PHP

Up until now, all of our code has been written in a single PHP file. But obviously, as your app grows this won’t work, and you’ll probably need to organize your code into multiple files.

We’re collapsing these functions in our IDE, but if we expand them, they just take up too much room and don’t really fit in with the “view” aspect of our app, so we’re going to move them over to their own file.

Let’s create a new file named functions.php in the root of our app. Then we can copy our functions over to this new file. Let’s expand out these functions, then add some whitespace to this file so it’s a bit easier to see. Whitespace is removed by the PHP processor, so we can add as many line breaks & indents as we like.

<?php declare(strict_types=1);

function getPosts(): array
{
    return [
        [
            'title' => 'How to learn PHP',
            'content' => 'This is how you learn PHP.',
        ],
        [
            'title' => 'How to learn MySQL',
            'content' => 'This is how you learn MySQL.',
        ],
        [
            'title' => 'How to learn Nginx',
            'content' => 'This is how you learn Nginx.',
        ],
    ];
}

function getPostText(int $numPosts): string
{
    return $numPosts === 1 ? 'post' : 'posts';
}

Now let’s close this file and go back to our index.php file, and remove the function code. We’ll leave our declare strict types at the top of the file, because I think keeping that line at the top of every PHP file in our app leads to more reliable PHP applications.

<?php declare(strict_types=1);

$title = 'My Blog';
$posts = getPosts();
$numPosts = count($posts);
$postText = getPostText($numPosts);
$numPostsDisplay = "$numPosts $postText";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php for ($i = 0; $i < $numPosts; $i++) : ?>
    <h3><?= $posts[$i]['title'] ?></h3>
    <p><?= $posts[$i]['content'] ?></p>
<?php endfor ?>

If we refresh our page, we can see that we get an error that says “Call to undefined function getPosts() on line 4”. We actually have multiple errors happening, but PHP only outputs the first error that occurs and than halts the remaining execution of the script.

You probably figured out that this getPosts() function is not found because there is no reference to the functions.php file that we created that contains this getPosts() function, along with the getPostText() function.

There are two ways to include a file in PHP, and they are both language constructs. One construct is named include, and the other is named require. You can call these constructs just like regular built-in PHP functions.

The difference between the two is that require requires the file to exist, and include doesn’t. So for example, if we write include('my-fancy-file.php') and refresh the page, notice that PHP outputs a warning, but it still continues the execution of the script, as our “call to undefined function getPosts()” error still occurs.

If we change this line to say require rather than include, then refresh the page, the “ call to undefined function” error never occurs, because further execution of the program is stopped. This means that “include” allows you to include optional files that may or may not exist, but “require” has a hard requirement on that file existing.

There are uses for each, but when in doubt always use require, as it will make your code more consistent & reliable in the long run. Let’s change my-fancy-file.php to our new functions.php file. When we reload the page, we’ll see that PHP includes our functions from the functions.php file. This essentially as the same effect as having the functions written out directly within our index.php file, but allows us to better organize & structure our code.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock