tags:

views:

70

answers:

3

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

+2  A: 
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);

Lizard
changeFruit also needs to return
Mez
Thanks missed that...edited accordingly
Lizard
+1  A: 

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);
Anax
+10  A: 

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
Mez
Thanks for digging into the question a little more. I forgot to add, that I can't return values!
Matt
I was about to write exactly this. Entirely correct and very complete. Clean answer and clear examples!
Paul Lammertsma
Thanks Paul - I tend to only answer if I'm not going to be giving one liners, and there's something I can go into in detail regarding :D
Mez