You can't get data into a function without arguments. In this lesson, we'll learn how to pass variables as arguments to PHP functions.
Instructor: [0:00] 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. [0:08] Since functions do not have access to outside scope, the idea of an argument was created in order for us to be able to pass data into a function.
[0:18] Arguments are passed to functions within parentheses, similar to how this count function executes and passes in the post variable. Let's create another function, this time for the post text.
[0:32] We will again use the function keyword, and we will name this function getPostText. Within this function, let's go ahead and copy the contents from this $postText variable into the function, and then we will return it.
[0:53] You'll notice that this $numPost variable is underlined within a squiggly, and it says it is undefined. We can move this $numPost and $post variable in to this function, but this breaks the single responsibility principle and our function is doing way too much.
[1:13] Remember that functions should only do one thing, and one thing only, so let's go ahead and back this out. Instead, we will pass this $numPost as an argument to this function. Within the open and closed parenthesis, we will go ahead and define our $numPost variable.
[1:33] You'll immediately see that this red squiggly goes away, so everything is valid now and the value of $numPost is satisfied by this variable that we are passing in as an argument.
[1:46] Since this expression is executed and a value is returned when we call getPostText, let's go ahead and replace the same text with a call to getPostText. Then we will pass in $numPost as an argument to the function.
[2:05] Just like count, we are calling the function and then passing in an argument to the function. When we save and go ahead and refresh the page, we will see that the code still executes exactly the same, as the variables are now properly passing into these functions and the results of the functions are properly returned to the same variables.