我有以下场景(简化):
function changeFruit($fruit) { changeAgain($fruit); } function changeAgain($fruit) { $fruit = "Orange"; } MAIN: $fruit = "Apple"; changeFruit($fruit); echo $fruit // Will show up as "Apple", How do I get it to show up as "Orange"??
编辑:忘记加入.情景不能使用返回声明 - 只是和$变量
谢谢!马特穆勒
当您将不是对象的东西传递给PHP中的函数时,php会在函数中复制该函数.
为了使它不使用副本,您需要告诉PHP您正在传递引用.
这是通过&运算符完成的
function changeFruit(&$fruit) { changeAgain($fruit); } function changeAgain(&$fruit) { $fruit = "Orange"; } $fruit = "Apple"; changeFruit($fruit); echo $fruit;
使用函数的返回值会更加明智和更好的实践(因为这样可以更容易阅读)
function changeFruit($fruit) { return changeAgain($fruit); } function changeAgain($fruit) { // do something more interesting with$fruit here $fruit = "Orange"; return $fruit; } $fruit = "Apple"; $fruit = changeFruit($fruit); echo $fruit