The Subtle Point of Return in PHP
After the return
statement is executed,
the function will finish its work. That is:
after return is executed, no further
code will be executed.
See the example:
<?php
function func($num) {
return $num * $num;
echo '!'; // this code will never execute
}
$res = func(3);
?>
This does not mean that a function must have
only one return
. But only one of them
will be executed.
In the following example, depending on the value
of the parameter, either the first or the second
return
will be executed:
<?php
function func($num) {
if ($num >= 0) {
return '+';
} else {
return '-';
}
}
echo func( 3); // will output '+'
echo func(-3); // will output '-'
?>
What will be output to the screen as a result of executing the following code:
<?php
function func($num) {
return $num;
$res = $num * $num;
return $res;
}
echo func(3);
?>
Explain why.
What will each echo
output as a result
of executing the following code:
<?php
function func($num) {
if ($num <= 0) {
return abs($num);
} else {
return $num * $num;
}
}
echo func(10);
echo func(-5);
?>
Explain why.
What will each echo
output as a result
of executing the following code:
<?php
function func($num) {
if ($num <= 0) {
return abs($num);
}
return $num * $num;
}
echo func(10);
echo func(-5);
?>
Explain why.