dongtang2376 2014-09-12 16:19
浏览 34
已采纳

php使用函数来改变函数外部变量的值

Im trying to change the value of a declared variable which is outside the function in use of a function

<?php
$test = 1;
function addtest() {
    $test = $test + 1;
}
addtest();
echo $test;
?>

but it seems it couldn't. only variables declared as parameters in the function only work. is there a technique for this? thanks in advance

  • 写回答

3条回答 默认 最新

  • duanju6788 2014-09-12 16:34
    关注

    Not sure if this is a contrived example or not, but in this case (as in most cases) it would be extremely bad form to use global. Why not just return the results and assign the return value?

    $test = 1;
    function increment($val) {
        return $val + 1;
    }
    $test = increment($test);
    echo $test;
    

    This way, if you ever need to increment any other variable besides $test, you're done already.

    If you need to change multiple values and have them returned, you can return an array and use PHP's list to easily extract the contents:

    function incrementMany($val1, $val2) {
        return array( $val1 + 1, $val2 + 1);
    }
    $test1 = 1;
    $test2 = 2;
    
    list($test1, $test2) = incrementMany($test1, $test2);
    echo $test1 . ', ' . $test2;
    

    You can use func_get_args to also accept a dynamic number of arguments and return a dynamic number of results as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?