也许我的问题有点基本或愚蠢,但我需要验证这一点。
我有一个php函数"functionA",它在for循环中被反复调用:
...
for($j=0; $j<$n_samples;$j++) {
if($type=='triband') {
functionA($arg1,$arg2);
}
}
...
和我的功能a:
...
functionA($arg1,$arg2) {
$wide_avg_txon = substr($bit_sequence,0,1);
if($wide_avg_txon==0)
{
echo " ---> is OFF...<br />";
}
else
{
echo " ---> is ON...<br />";
// if is ON then skip execution of code inside the function
return;
}
// DO SOME STUFF!
}
...
所以简单地说,我不想在functionA中执行其余的代码,如果"$wide_avg_txon==1",我只是想继续执行下一次迭代的for循环!
上面的代码会工作吗?'return'和'return false'之间的区别是什么?'return false'是否也能工作:
...
if($wide_avg_txon==0)
{
echo " ---> is OFF...<br />";
}
else
{
echo " ---> is ON...<br />";
// if is ON then skip execution of code inside the function
return false;
}
谢谢!
您的return
将工作,因为您对返回的结果不感兴趣。你只需要继续for循环。
如果你有一个测试的代码结构,你想知道测试的结果,那么你可以使用return false
让其余的代码知道测试失败。
你的函数a将完美地工作,但为了可读性起见,最好这样格式化:
...
function functionA($arg1, $arg2) {
$wide_avg_txon = substr($bit_sequence,0,1);
// if is ON then skip execution of code inside this function
if ($wide_avg_txon != 0) {
echo " ---> is ON...<br />";
return;
}
echo " ---> is OFF...<br />";
// DO SOME STUFF!
}
...
不同之处在于,您可以立即取消不想要的"ON"条件,并尽快退出函数。然后,函数的其余部分将处理您想要做的任何事情,而不是坐在if语句块中。
函数将在返回语句后停止。你可以在这里阅读更多内容:http://php.net/manual/tr/function.return.php
作为例子,你可以这样测试:
<?php
$_SESSION['a'] = "Naber";
function a(){
return;
unset($_SESSION['a']);
}
a(); // Let see that is session unset?
echo $_SESSION['a'];
?>
谢谢
return false
返回布尔值false
。return
将返回NULL
。两者都不会执行任何后续代码。
因此,扩展RST的答案,两个返回值都不满足if
条件:
if(functionA($arg1,$arg2))
echo'foo';
else
echo'bar';
bar
将被回显。
这可能是有用的,如果你有:
$return=functionA($arg1,$arg2);
if($return===NULL)
echo'Nothing happened';
elseif($return===false)
echo'Something happened and it was false';
else
echo'Something happened and it was true';
NULL
非常有用