Passing arguments to PHP functions

We just learned how to get the resulting value executed from a function, but we didn’t yet learn how to pass data to a function. Since functions do not have access to outside scope, the idea of an “argument” was created in order for us to pass data into a function.

Arguments are passed to functions within parenthesis, similar to how this count() function is written.

Let’s create another function, this time for the post text. We will again use the function keyword, and name this function getPostText().

Within this function let’s go ahead and copy the current contents of the $postText variable into this function, and make sure it is the returned value of this function.

<?php
...
function getPostText()
{
    return $numPosts === 1 ? 'post' : 'posts';
}
$title = 'My Blog';
$posts = getPosts();
$numPosts = count($posts);
$postText = 
$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 ?>

Note how we have a $numPosts variable, but that it is underlined in a red squiggly, which is again telling us that this is an undefined variable.

We can move our call to the count() function in this getPostText function, but this breaks the single responsibility principle by making our function code do more than one thing. Remember that functions are only supposed to do one small thing to make sure they are reliable and easy to understand.

So rather than doing that, we will instead pass the $numPosts variable into our function as an argument.

To do this, lets specify the $numPosts variable within the open and close parenthesis. You’ll immediately see that our red squiggly goes away, which satisfies the value of the $numPosts variable within the function.

We can now assign a value to the $postText variable, which will be a call to our newly created function, getPostText(). And just like the count() function, we will pass in the value of $numPosts as an argument to this function.

<?php
...
function getPostText($numPosts)
{
    return $numPosts === 1 ? 'post' : 'posts';
}
$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 ?>

When we refresh the page, we will see that the code still executes, as the variables are now being properly passed into our functions, and the results of those functions are properly returned to the same variables.

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