假设以下代码:
function doStuff($rowCount) {
$rowCount++;
echo $rowCount.' and ';
return $rowCount;
}
$rowCount = 1;
echo $rowCount.' and ';
doStuff($rowCount);
doStuff($rowCount);
doStuff($rowCount);
?>
所需的输出是
1 and 2 and 3 and 4 and
实际输出为
1 and 2 and 2 and 2 and
我想我是在误解在这种情况下“返回”是如何工作的.我怎样才能最好地做到这一点?
解决方法:
您要么必须将doStuff调用的返回值分配回本地$rowCount变量:
$rowCount = 1;
echo $rowCount.' and ';
$rowCount = doStuff($rowCount);
$rowCount = doStuff($rowCount);
$rowCount = doStuff($rowCount);
或者您通过放置&将变量传递为reference.在形式参数$rowCount之前:
function doStuff(&$rowCount) {
$rowCount++;
echo $rowCount.' and ';
return $rowCount;
}
现在,函数doStuff中的形式参数$rowCount引用的值与函数调用中传递给doStuff的变量的值相同.
标签:php,variables,return
来源: https://codeday.me/bug/20191012/1896654.html
本文探讨了PHP中函数使用及变量引用的方法。介绍了如何通过返回值更新变量与使用引用传递来实现期望的功能。

被折叠的 条评论
为什么被折叠?



