PHP:将变量传递给函数,对变量执行某些操作,然后将其返回

时间:2010-08-26 17:24:38

标签: php variables return

假设以下代码:

<?php
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

我认为我理解“回归”在这种情况下是如何运作的。我怎么能最好地完成这个?

5 个答案:

答案 0 :(得分:10)

您必须将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;
}

现在函数$rowCount中的形式参数doStuff指的是与函数调用中传递给doStuff的变量相同的值。

答案 1 :(得分:2)

你应该试试这个:

$rowCount = 1;
echo $rowCount.' and ';
$rowCount = doStuff($rowCount);
$rowCount = doStuff($rowCount);
$rowCount = doStuff($rowCount);

您的doStuff()方法返回一个在您没有分配时只使用语句doStuff($rowCount);时从未使用过的int。

答案 2 :(得分:1)

更改function doStuff($rowCount)

function doStuff(&$rowCount)

通常在PHP中,您要将变量的副本发送给函数,因此函数内的修改不会影响函数外部变量的值。添加&符号告诉PHP发送对变量的引用,因此对变量的修改会传播回调用者。

答案 3 :(得分:1)

我会尝试修复代码:...

<?php
function doStuff($rowCount) {
    $rowCount++;
    echo $rowCount.' and ';
    return $rowCount;
}
$rowCount = 1;
echo $rowCount.' and ';
doStuff(doStuff(doStuff($rowCount)));

?>

答案 4 :(得分:1)

你需要传递变量'by reference'而不是'by value'来完成这个添加&amp;到函数声明中的变量:

function doStuff(&$rowCount);

另请查看PHP: Passing by Reference

相关问题