Get variables from the outside, inside a function in PHP

徘徊边缘 提交于 2019-12-17 10:56:52

问题


I'm trying to figure out how i can use a variable, that has been set outside a function, inside. Is there any way of doing this? I've tried to set the variable to "global" but it doesn't seems to work out as expected.

A simple example of my code

$var = '1';

function() {
$var + 1;
return $var;
}

i want this, to return the value of 2.


回答1:


You'll need to use the global keyword inside your function. http://php.net/manual/en/language.variables.scope.php

EDIT (embarrassed I overlooked this, thanks to the commenters)

...and store the result somewhere

$var = '1';
function() {
    global $var;
    $var += 1;   //are you sure you want to both change the value of $var
    return $var; //and return the value?
}



回答2:


Globals will do the trick but are generally good to stay away from. In larger programs you can't be certain of there behaviour because they can be changed anywhere in the entire program. And testing code that uses globals becomes very hard.

An alternative is to use a class.

class Counter {
    private $var = 1;

    public function increment() {
        $this->var++;
        return $this->var;
    }
}

$counter = new Counter();
$newvalue = $counter->increment();



回答3:


$var = 1;

function() {
  global $var;

  $var += 1;
  return $var;
}

OR

$var = 1;

function() {
  $GLOBALS['var'] += 1;
  return $GLOBALS['var'];
}



回答4:


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;
}



回答5:


This line in your function: $var + 1 will not change the value assigned to $var, even if you use the global keyword.

Either of these will work, however: $var = $var + 1; or $var += 1;




回答6:


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



回答7:


<?php
$var = '1';
function x ($var) {
return $var + 1;
}
echo x($var); //2
?>


来源:https://stackoverflow.com/questions/5060465/get-variables-from-the-outside-inside-a-function-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!