PHP:将变量传递给函数,对变量执行某些操作,然后将其返回 [英] PHP: pass a variable to a function, do something to the variable, return it back

查看:49
本文介绍了PHP:将变量传递给函数,对变量执行某些操作,然后将其返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设代码如下:

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

我认为我很困惑返回"在这种情况下是如何工作的.我怎样才能最好地做到这一点?

I take it I'm musunderstanding how "return" works in this context. How could I best accomplish this?

推荐答案

您要么必须将 doStuff 调用的返回值分配回本地 $rowCount 变量:

You either have to assign the return value of the doStuff calls back to the local $rowCount variable:

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

或者您通过放置 & 将变量作为 reference 传递在形参$rowCount前:

Or you pass the variable as a reference by putting a & in front of the formal parameter $rowCount:

function doStuff(&$rowCount) {
    $rowCount++;
    echo $rowCount.' and ';
    return $rowCount;
}

现在函数doStuff中的形参$rowCount所指的值与函数中传递给doStuff的变量相同打电话.

Now the formal parameter $rowCount inside the function doStuff refers to the same value as the variable that is passed to doStuff in the function call.

这篇关于PHP:将变量传递给函数,对变量执行某些操作,然后将其返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆