开发者

Get variables from the outside, inside a function in PHP

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 to "global" but it doesn't seems to work out as expected.

A simple exa开发者_JS百科mple of my code

$var = '1';

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

I want this to return the value of 2.


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


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();


$var = 1;

function() {
  global $var;

  $var += 1;
  return $var;
}

OR

$var = 1;

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


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


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


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;


According to : https://riptutorial.com/php/example/2496/global-variable-best-practices it's better to put

$var = '1';

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

correct me if I got it wrong.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜