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.
Example: creates a function that returns the sum of two numbers.
<?php
function multiply($firstnum, $secondnum) {
$result = $firstnum * $secondnum;
return $result;
}
echo multiply(9,5);
//will print "45"
?>
Put these lines into a text file called multiply.php and place this file in your web server document root. When you access this script through your web browser, it produces the following:
45
Notice in line 2 that multiply() should be called with two numeric arguments (line 6 shows those to be 9 and 5 in this case). These values are stored in the variables $firstnum and $secondnum. Predictably, multiply() multiplies 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);
No comments:
Post a Comment