Get variables from the outside, inside a function in PHP

82,198

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

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

Solution 3

$var = 1;

function() {
  global $var;

  $var += 1;
  return $var;
}

OR

$var = 1;

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

Solution 4

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

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

Share:
82,198
Henrikz
Author by

Henrikz

Updated on February 28, 2021

Comments

  • Henrikz
    Henrikz about 3 years

    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 example of my code

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

    I want this to return the value of 2.

  • Joakim Bodin
    Joakim Bodin about 13 years
    $var = '1'; function() { global $var; $var + 1; return $var; }
  • Henrikz
    Henrikz about 13 years
    Bah, it's just too easy! Anyway, huge thanks for the quick reply! Cheers mate!
  • Admin
    Admin about 13 years
    generally not recommended to use global any more than absolutely necessary
  • David Harkness
    David Harkness about 13 years
    Even provided access via global, the statement $var + 1; evaluates to 2 but doesn't store the result anywhere. Try $var++; or $var += 1;, but note that it changes the original variable as well.
  • devios1
    devios1 over 11 years
    Since you're not answering the question, I think this would have made more sense as a comment. It is correct nevertheless.
  • GordonM
    GordonM over 7 years
    +1 for being a far better solution than global state, but it may also be necessary for there to be a getter for $var for cases when somebody only wants the current value without incrementing it