[ Team LiB ] Previous Section Next Section

Returning Values from User-Defined Functions

In our previous example, we output an amended string to the browser within the printBR() function. Sometimes, however, you will want a function to provide a value you can work with yourself. If your function has transformed a string you have provided, you might want to get the amended string back so you can pass it to other functions. A function can return a value using the return statement in conjunction with a value. return stops the execution of the function and sends the value back to the calling code.

Listing 6.4 creates a function that returns the sum of two numbers.

Listing 6.4 A Function That Returns a Value
 1: <!DOCTYPE html PUBLIC
 2:    "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 6.4 A Function That Returns a Value</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: function addNums( $firstnum, $secondnum ) {
12:   $result = $firstnum + $secondnum;
13:   return $result;
14: }
15: print addNums(3,5);
16: // will print "8"
17: ?>
18: </div>
19: </body>
20: </html>

The script in Listing 6.4 prints the number 8. Notice in line 11 that addNums() should be called with two numeric arguments (line 15 shows those to be 3 and 5 in this case). These are stored in the variables $firstnum and $secondnum. Predictably, addNums() adds the numbers contained in these variables together and stores the result in a variable called $result.

The return statement can return a value or nothing at all. How a value passed by return is arrived at can vary. The value could be hard-coded:


return 4;

It could also be the result of an expression:


return ( $a/$b );

Finally, it could be the value returned by yet another function call:


return ( another_function( $an_argument ) );


    [ Team LiB ] Previous Section Next Section