Returning Values from FunctionsSo 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:
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:
Now you can call this function just as you would call and use a normal built-in PHP function:
And here's what you see in this case:
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:
And here's what you get:
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:
And you get the same result as before:
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. |
Tuesday, December 22, 2009
Returning Values from Functions
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment