Tuesday, December 22, 2009

Returning Values from Functions








Returning Values from Functions


So far, so good with functions. But they're designed to return values, and although we've used built-in PHP functions that do that throughout the book already, we haven't written any of our own that do that.


To return a value from a function, you use the return statement. Here's how you use it:



return (value);


The parentheses (which make return look like a function even though it's actually statement) are optional. For instance, PHP doesn't come with a handy square function to square numbers, but you can create one using return like this:



<?php
function square($value)
{
return $value * $value;
}
?>


Now you can call this function just as you would call and use a normal built-in PHP function:



<?php
echo "What's 16 x 16? Why, it's ", square(16), ".";

function square($value)
{
return $value * $value;
}
?>


And here's what you see in this case:



What's 16 x 16? Why, it's 256.


You can also return boolean values, just as you might return any other value. For instance, say you wanted to check whether it's a nice day outside with a function check_temperature. This function should return TRUE if it's a nice day and FALSE otherwise. Here's what that might look like:



<?php
$degrees = 67;

if(check_temperature($degrees)){
echo "Nice day.";
}
else {
echo "Not so nice day.";
}

function check_temperature($temperature)
{
$return_value = FALSE;
if($temperature > 65 && $temperature < 75){
$return_value = TRUE;
}
return $return_value;
}
?>


And here's what you get:



Nice day.


You're not restricted to a single return statement in a function; you can have as many as you like. Just bear in mind that when a return statement is executed, you leave the function and jump back to the code that called the function in the first place. For instance, here's what converting the previous example to using two return statements looks like:



<?php
$degrees = 67;

if(check_temperature($degrees)){
echo "Nice day.";
}
else {
echo "Not so nice day.";
}

function check_temperature($temperature)
{
if($temperature > 65 && $temperature < 75){
return TRUE;
}
return FALSE;
}
?>


And you get the same result as before:



Nice day.


The return statement is one of the things that really makes functions, well, functional. With this statement, you can use functions to process data and send the results back to the calling code. That's very useful when you're using functions to break up your code and want to have each function return the results of its internal work.








    No comments: