Get variables from the outside, inside a function in PHP

前端 未结 7 1975
时光说笑
时光说笑 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: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();
    

提交回复
热议问题