开发者

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)开发者_如何学Go{
    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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜