Today, I’m going to continue on with my interpretation, or should I say – basically – my notes, on Hampton Paulk’s “PHP Functions” class over at Treehouse. I’ve been enjoying Hampton’s style and his teaching is remarkably understandable.
In this post, I’m going to go over PHP function returns. Now, before I started writing today, I did a little Google search for the title of this post and nothing immediately popped up. Something called, “Returning Values in PHP” was returned, but obviously, that doesn’t precisely hit the mark. I’ll have to see where he’s going with this one. With that said, let’s dive into it.
PHP return Statement
What we’re talking about here is the return statement in PHP. I found a few definitions of this statement and listed them below. Here they are:
PHP.net
“Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.”
W3Resource
“PHP return statement immediately terminates the execution of a function when it is called from within that function. This function is also used to terminate the execution of an eval() function or script file. If this function is called from global scope, the function stops the execution of the current script. If the current script file was included using include() or required(), then control goes back to the calling file.”
Hampton basically says that by having a function return a value, we’ll be able to store data from a function call to any type of a value variable. He says the return statement will immediately end the function’s execution as well, returning control back to where the function call resides. So, as you can see, I think I’m on the right track with this one. Hampton’s definition is in line with the other two I listed above.
Now that that’s out of the way, let’s get into some code examples so we can see what these return statements look like. And as usual, I’ll mix these examples up as to make them my own. I like to stretch the imagination. Also, if you’re practicing your own PHP and would like to play around and run these examples, you can do just that over at Runnable. That’s where I test out my PHP code online.
Regular Return
<?php function test() { return "This is the function output."; } $output = test(); echo $output; ?>
In the above code, we’ve got a few things going on. First, we’ve got a function. You’ve seen those before from my previous post about PHP functions. The thing is, inside this function, we’ve got one of those “return” statements, instead of an “echo” statement. So, like I said above, by using the return statement, we can store the function output value inside a variable. That’s what we’re doing above – storing the string inside a variable called, “$output” that’s outside the function. Lastly, we’re now echoing the variable, which gives us the ultimate output of:
This is the function output.
Pretty cool.
If we wanted to throw an if/else statement into our function, we could do that like this:
if/else Statement
<?php function test($input) { if($input == "One") { return "This is the first function output."; } else { return "This is the second function output."; } } $output = test("One"); echo $output; ?>
In this case, the output would be:
This is the first function output.
If we included anything other than “One” when we called the function, the output would have been:
This is the second function output.
Here’s a fun one. It’s going to take some more looking at, but I think it’s rather straight forward.
Calculating Integers
<?php function sum($x, $y) { return $x + $y; } $total = sum(5, 9); echo $total; ?>
In the above code, I created a function called “sum” that allows two arguments. Inside the function, I’m adding the arguments and returning them outside the function. Outside the function, I’m passing the function two integers – in this case – 5 and 9 and storing the result of them in a variable called $total. Finally, I’m echoing the $total variable and in this case, the output is:
14
I do want to point out one strange occurrence. In the video I’m watching with Hampton, he said that he couldn’t name his function “sum” because it’s an “internal word.” Therefore, he named his “add_up” instead. I thought that sounded peculiar because I’ve seen other functions with the name of sum and they worked fine. I went ahead and named mine sum as well and it works. I’m wondering it Hampton avoided this word out of safety or if it was based on something I’m missing. I’ll have to look into this later on.
Not Storing in a Variable
I was looking through W3Schools and came across an example of adding and returning integer values. It’s different because in the example they gave, they don’t store anything in a variable. Here, take a look at the example:
<?php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = " . sum(5,10) . "<br>"; echo "7 + 13 = " . sum(7,13) . "<br>"; echo "2 + 4 = " . sum(2,4); ?>
The result of this is:
5 + 10 = 15
7 + 13 = 20
2 + 4 = 6
I went ahead and changed the code around to look like this:
<?php function sum($x, $y) { $z = $x + $y; return $z; } $total1 = sum(5,10); $total2 = sum(7,13); $total3 = sum(2,4); echo "5 + 10 = " . $total1 . "<br>"; echo "7 + 13 = " . $total2 . "<br>"; echo "2 + 4 = " . $total3; ?>
I got the same exact result, which just goes to show, there’s more than one way to skin a cat.
Using print_r
In this next example, we’re going to pass in two integers to our function, create an array inside the function and then return the array. We’ll use the print_r function to output the information about the array.
<?php function sum($x, $y) { $arr = array( $x, $y, $x + $y ); return $arr; } $total = sum(5, 9); print_r($total); ?>
The output for this function is:
Array ( [0] => 5 [1] => 9 [2] => 14 )
If you aren’t aware of what the print_r function is, it’s one of PHP’s internal functions that displays human-readable information about a variable. In the case above, the variable is called “$arr” and has the array stored in it. If we didn’t use the print_r function and simply went ahead trying to echo our result, like we did in the previous examples, the output would have been “Array.”
Now, looking a bit closer at the output for the above example, it’s important to note that what’s output for this array is the key (position in the array) and the result for each line inside the array. So, what we have above is key 0 with the result of 5, key 1 with the result of 9 and key 2 with the result of 14.
I’m not sure the previous output is entirely useful, so let’s take a look at how to pull out just one line, or key position in this above array. Take a look at the following code:
<?php function sum($x, $y) { $arr = array( $x, $y, $x + $y ); return $arr; } $total = sum(5, 9); echo $total[2]; ?>
Notice how the last line is changed. Instead of:
print_r($total);
We’ll use:
echo $total[2];
To output just the third key position in the array. In this case, the output is:
14
Variable Functions
This section sort of threw me when I watched the movie on Treehouse. I’m not sure enough information was given as background as to why I would want to use a variable function. And as I write this, I’m still not sure what a “callback” is or how it would be helpful. But Hampton hasn’t let me down yet, so I’ll give him the benefit of the doubt when he says, “We’ll go over callbacks in a later lesson.”
For now though, I’m going to take his example, just the way he wrote it and copy it here. Then, I’m going to attempt to make sense of it as I type. Here goes.
<?php function answer(){ return 42; } function add_up($a, $b){ return $a + $b; } $func = "answer"; echo $func(); ?>
Okay, so this is his first example. What we’re doing here is using only the first function called “answer.” Towards the bottom, we’re creating a variable and calling the function by using a string called “answer.” I’ll admit, this is where it gets confusing. I understand how this is working – in this case, the string is the name of the function, but what happens if we really wanted to store a string of text called “answer” in a variable? Would it still call the function? I’m sure I just haven’t learned something yet.
Perhaps the next line gives us more information. From what I’m gathering, the variable called $func is simply set to a string called “answer.” That’s really just a string. It doesn’t turn into anything special until you add an open and closed parenthesis after the variable. It’s only then that the string inside that variable comes alive and calls the function. Does that make sense?
Let’s go over this one more time. Right here, we have a function called “answer.”
function answer(){ return 42; }
And here, we have a simple string of text called “answer” set to a variable named $func. This is straightforward and as of right now, still just a string.
$func = "answer";
Finally, we can call the “answer” function, by first calling the string inside the $func variable. We’ll do this by adding two parenthesis after the $func variable and echoing it. It’s that simple
echo $func();
And for this whole example, we get the output of:
42
We get this because really, all the initial function did was return that value.
Boy, that was confusing, but I think I get it now.
Hampton gives another example. Here it is:
<?php function answer(){ return 42; } function add_up($a, $b){ return $a + $b; } $func = "answer"; $num = $func(); echo $num; ?>
There really isn’t much changed here. All he did was set the $func() call to a variable called $num. Then, he echoed the $num variable and got the same result, which is:
42
But wait, there’s more. Take a look at this next example:
<?php function answer(){ return 42; } function add_up($a, $b){ return $a + $b; } $func = "add_up"; $num = $func(5, 10); echo $num; ?>
In this example, all we did was change the string in the $func variable to the name of the next function, which is “add_up.” Now, by calling the $num variable at the bottom, we’re calling the $func variable with the newly placed arguments right above it, which in turn, calls the $func variable with the string of “add_up” right above that, which in turn, calls the function called “add_up” and passes two values into it to add up. For all this work, we get the output:
15
Hampton promises this is very handy. Again, we’ll go over why in later lessons. For now, I think I’ll I’ll just tuck it in the back of my mind somewhere to use at a later date. I do get it though, and I guess that’s the most important. If you’d like to read up on variable functions in your free time, please feel free to browse through this page.
PHP Closures
Do you know what a PHP closure is? Well, if you don’t, please read this:
Hampton
“Closures are anonymous functions, which are functions with no name, that are capable of accessing variables outside of the function scope.”
PHP.net
“Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.”
Closures seem to simply be a function that’s set to a variable that has special powers. Before we get into those powers, let’s look at what an anonymous function that’s set to a variable looks like:
<?php $greet = function(){ echo "Hello there."; }; $greet(); ?>
In the first line, we have a variable named “$greet” and that’s equal to an anonymous function. Inside the function is a simple string that will be echoed when the function is called. Below the function, we have the function call. The output for this is:
Hello there.
Now it’s time to spice things up a bit and talk about the special powers of a closure. Typically, functions can’t access variables that are set outside of the function in question. This is called being outside of the function “scope.” When dealing with a closure though, we can take advantage of a keyword called “use” that allows us to go outside of a function and grab a variable and then pull that variable back inside the function. Take a look at this example:
<?php $name = "Jay"; $greet = function() use($name){ echo "Hello $name."; }; $greet(); ?>
As you can see, we created a variable that’s outside of the function scope. This is a variable named “$name” and it’s equal to Jay. In order for the function to access this variable, we wrote the keyword “use” and then parenthesis with the variable $name inside of it. The “use” is instrumental in allowing the usage of the outside variable. Then, inside the function, we take advantage of the $name variable and echo out:
Hello Jay.
This seems more straightforward than the last section, but they were all fun.
Unfortunately, this is the end of this post. If you have any comments or questions (or advice), please leave everything down in the comment section below.
Leave a Reply