Refactoring functions into PHP classes

Let’s create a new file in the classes directory named Post.php. We will move the contents from our functions.php file into this new class.

Each of these functions really needs a scope defined. The default scope is public, but it’s still a good idea to explicitly define these scopes as public to make it very apparent this is what we want to do.

We also need to update the function names, removing any reference to post from them. Since post is already implied by the class name of Post, naming these functions with post in the name is redundant.

Since we really don’t need or want to instantiate this class, we can also use the static keyword to define this as a static function. This means that we won’t have to instantiate this class to call one of it’s functions — we can just call the functions directly.

<?php declare(strict_types=1);


class Post
    public static function getAll(): array
        $author1 = new Author('Mark Shust');
        $author2 = new Author('Betsy Sue');

        return [
                'title' => 'How to learn PHP',
                'content' => 'This is how you learn PHP.',
                'author' => $author1->getName(),
                'title' => 'How to learn MySQL',
                'content' => 'This is how you learn MySQL.',
                'author' => $author1->getName(),
                'title' => 'How to learn Nginx',
                'content' => 'This is how you learn Nginx.',
                'author' => $author2->getName(),

    public static function getText(int $numPosts): string
        return $numPosts === 1 ? 'post' : 'posts';

Now that we copied all of the functionality from the functions.php file, it is no longer needed, so we can delete this file.

We will also need to update the index.php file to include our new Post class located at classes/Post.php. Then, we can update the references for the $posts and $numPostsDisplay variables.

We will call the Post class, but since we don’t need to instantiate this class, we can call the public static functions we defined with two colons, then the name of the class. So this first call will be to Post::getAll(), and the second will be a call to Post::getText().

<?php declare(strict_types=1);


$title = 'My Blog';
$posts = Post::getAll();
$numPosts = count($posts);
$postText = Post::getText($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>
    <p>By <?= $posts[$i]['author'] ?></p>
<?php endfor ?>

And if we re-test executing this code, we’ll see everything still functions as we would expect.

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