我有以下场景(简化):
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"??
编辑:忘了加入。情景不能使用退货声明 - 只是&$变量
谢谢! 马特穆勒
答案 0 :(得分:10)
当您将不是对象的东西传递给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
答案 1 :(得分:2)
function changeFruit($fruit) {
return changeAgain($fruit);
}
function changeAgain($fruit) {
return $fruit = "Orange";
}
MAIN:
$fruit = "Apple";
$fruit = changeFruit($fruit);
echo $fruit;
希望有所帮助!
注意:从changeAgain函数返回并覆盖$ fruit = changeFruit($ fruit);
答案 2 :(得分:1)
您没有从函数中返回值。试试这个:
function changeFruit($fruit) {
return changeAgain($fruit);
}
function changeAgain($fruit) {
$fruit = "Orange";
return $fruit;
}
MAIN:
$fruit = "Apple";
$fruit = changeFruit($fruit);