简体   繁体   中英

Redefining a PHP variable by referencing the variable in a function?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM