Get variables from the outside, inside a function in PHP

前端 未结 7 1921
时光说笑
时光说笑 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:09
    $var = 1;
    
    function() {
      global $var;
    
      $var += 1;
      return $var;
    }
    

    OR

    $var = 1;
    
    function() {
      $GLOBALS['var'] += 1;
      return $GLOBALS['var'];
    }
    
    0 讨论(0)
  • 2020-12-03 07:12
    <?php
    $var = '1';
    function x ($var) {
    return $var + 1;
    }
    echo x($var); //2
    ?>
    
    0 讨论(0)
  • 2020-12-03 07:15

    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;

    0 讨论(0)
  • 2020-12-03 07:23

    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?
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-03 07:28

    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();
    
    0 讨论(0)
提交回复
热议问题