Matt
Matt

Reputation: 22911

PHP function confusion

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

Upvotes: 0

Views: 100

Answers (3)

Mez
Mez

Reputation: 24933

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

Upvotes: 10

Anax
Anax

Reputation: 9372

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);

Upvotes: 1

Lizard
Lizard

Reputation: 44992

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);

Upvotes: 2

Related Questions