If return statement is called from within a function, it immediately ends execution of the current function, and returns its argument as the value of the function call. If it is called from the global scope, then execution of the current script file is ended. If the current script file was included, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call.
If return is called from within the init.php file, then script execution ends.
Syntax | Description |
---|---|
return argument; | ends execution of current function or script and returns argument. The argument can be omitted. |
<?php
function func() // declare a user-define function fun()
{
$var1 = 1;
return $var1; // return $var1 (1)
}
$var2 = 2;
$var3 = func(); // assign $var1 to $var3 by func()
$result = $var2 + $var3; // 2 + 1 = 3
echo $result;
?>
[result]
3
test.php |
---|
<?php
$var2 = 2;
$var3 = 3;
return ($var2 + $var3); // return 5
?>
init.php |
---|
<?php
$var1 = include_once "test.php";
echo $var1;
?>
[result]
5
<?php
$var1 = 1;
echo ++$var1; // statement is executed
echo ++$var1; // statement is executed
return; // ends script
echo ++$var1; // statement will be never executed
?>
[result]
23