I have the following scenario (simplified):
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"??
EDIT: FORGOT TO ADD. THE SCENARIO CANNOT USE RETURN STATEMENTS - JUST &$variable
Thanks! Matt Mueller
-
2To the person who downvoted the question, you should seriously go back and check your very first code.Anax– Anax2009年10月20日 10:18:24 +00:00Commented Oct 20, 2009 at 10:18
-
3And also, good practice to leave a comment if you downvote a question, to help improve the question)Mez– Mez2009年10月20日 10:22:05 +00:00Commented Oct 20, 2009 at 10:22
-
Anax: It wasn't me who downvoted you, but it seems that you haven't read much of the manual. Try this: php.net/manual/en/functions.arguments.phpTom– Tom2009年10月20日 12:59:19 +00:00Commented Oct 20, 2009 at 12:59
-
Hey I don't want to start a flame war here.. the issue DID NOT involve return statements.. I wanted more information on &$variable. I apologize it was late and a poorly written question and description, but my question's intent was not entirely trivial.Matt– Matt2009年10月21日 00:09:59 +00:00Commented Oct 21, 2009 at 0:09
3 Answers 3
When you pass something that is not an object to a function in PHP, php makes a copy of that to use within the function.
To make it not use a copy, you need to tell PHP you are passing a reference.
This is done with the & operator
function changeFruit(&$fruit) {
changeAgain($fruit);
}
function changeAgain(&$fruit) {
$fruit = "Orange";
}
$fruit = "Apple";
changeFruit($fruit);
echo $fruit;
It would be more sensible, and better practice, to use return values of the functions (as this makes things easier to read)
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
3 Comments
function changeFruit($fruit) {
return changeAgain($fruit);
}
function changeAgain($fruit) {
return $fruit = "Orange";
}
MAIN:
$fruit = "Apple";
$fruit = changeFruit($fruit);
echo $fruit;
Hope that helps!
Note: the return from the changeAgain function and overwriting $fruit = changeFruit($fruit);
1 Comment
You are not returning the values from your functions. Try this:
function changeFruit($fruit) {
return changeAgain($fruit);
}
function changeAgain($fruit) {
$fruit = "Orange";
return $fruit;
}
MAIN:
$fruit = "Apple";
$fruit = changeFruit($fruit);