Get variables from the outside, inside a function in PHP

前端 未结 7 1920
时光说笑
时光说笑 2020-12-03 06:31

I\'m trying to figure out how I can use a variable that has been set outside a function, inside a function. Is there any way of doing this? I\'ve tried to set the variable t

7条回答
  •  有刺的猬
    2020-12-03 07:26

    See http://php.net/manual/en/language.variables.scope.php for documentation. I think in your specific case you weren't getting results you want because you aren't assigning the $var + 1 operation to anything. The math is performed, and then thrown away, essentially. See below for a working example:

    $var = '1';
    
    function addOne() {
       global $var;
       $var = $var + 1;
       return $var;
    }
    

提交回复
热议问题