开发者

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

开发者 https://www.devze.com 2023-03-08 12:51 出处:网络
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.

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

精彩评论

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