0

Gee Wiz finding the vocab to express the question can be pretty tricky, but hopefully you can tell me what's wrong with referencing a variable in a function in order to change it.

Example:

    <?php
$a = 5;
$something = 5;

function changeIt($it){
    global $a;
    $it = $it * $a;
};

changeIt($something);

echo $something;
    ?>

This returns 5, so the global variable $something hasn't been redefined.

7
  • 1
    ... not calling changeIt for one, not using reference variables for another. php.net/manual/en/language.references.php . Use &$it in your function declaration instead. Commented May 26, 2011 at 23:42
  • 1
    Your not calling changeIt(). Furthermore, what do you want to change? Commented May 26, 2011 at 23:42
  • As both minitech and Jason noted you are doing a number of thing incorrectly. It would be very helpful if you told us what exactly you are trying to achieve, forget about the code. Commented May 26, 2011 at 23:44
  • Be more specific in what you are trying to do. Are you trying to return the value of $it? make sure you return $it . Are you trying to modify the value of the variable that $it references in a pass by reference type of way? Make sure you specify that you are passing by reference function changeIt(&$it) . Commented May 26, 2011 at 23:49
  • 1
    Any explanation on the downvotes, people? Commented May 26, 2011 at 23:53

1 Answer 1

5

You need to pass $it by reference, and also call changeIt:

<?php
    function changeIt(&$it){
       global $a;
       $it = $it * $a;
    }

    $a = 5;
    $something = 5;

    changeIt($something);
?>

http://ideone.com/9RQQW

Sign up to request clarification or add additional context in comments.

5 Comments

Just guessing that he wants to do changeIt($something), since he's used $a as a global, but $something is unused.
+1 for the correct answer and also for including the totally unused $something in it...
Hey please check my code above and please tell me why you need that ampersand?
@3Dom: You need the ampersand to pass the variable by reference. See the link I posted as a comment to your question.
Passing by reference. Now there's another obscure operation I wouldn't have thought necessary, but hey, super duper spot on mate. You have made me a happy man.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.