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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog