Specifications

Returning from Functions
The keyword return stops the execution of a function. When a function ends because either all
statements have been executed or the keyword return is used, execution returns to the statement
after the function call.
If you call the following function, only the first echo statement will be executed.
function test_return()
{
echo “This statement will be executed”;
return;
echo “This statement will never be executed”;
}
Obviously, this is not a very useful way to use return. Normally, you will only want to return
from the middle of a function in response to a condition being met.
An error condition is a common reason to use a return statement to stop execution of a func-
tion before the end. If, for instance, you wrote a function to find out which of two numbers
was greater, you might want to exit if any of the numbers were missing.
function larger( $x, $y )
{
if (!isset($x)||!isset($y))
{
echo “this function requires two numbers”;
return;
}
if ($x>=$y)
echo $x;
else
echo $y;
}
The built-in function isset() tells you whether a variable has been created and given a value.
In this code, we are going to give an error message and return if either of the parameters has
not been set with a value. We test this by using !isset(), meaning NOT isset(), so the if
statement can be read as if x is not set or if y is not set. The function will return if either of
these conditions is true.
If the return statement is executed, the subsequent lines of code in the function will be
ignored. Program execution will return to the point at which the function was called. If both
parameters are set, the function will echo the larger of the two.
The output from the following code:
$a = 1;
$b = 2.5;
Using PHP
P
ART I
140
07 7842 CH05 3/6/01 3:35 PM Page 140