Returning Values from User-Defined Functions


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

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

Listing 7.4. A Function That Returns a Value
 1: <?php 2: function addNums($firstnum, $secondnum) { 3:     $result = $firstnum + $secondnum; 4:     return $result; 5: } 6: echo addNums(3,5); 7: //will print "8" 8: ?> 

Put these lines into a text file called addnums.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

 8 

Notice in line 2 that addNums() should be called with two numeric arguments (line 6 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 and stores the result in a variable called $result.

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

 return 4; 

It can be the result of an expression:

 return $a/$b; 

It can be the value returned by yet another function call:

 return another_function($an_argument); 



Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net