Get variables from the outside, inside a function in PHP
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;
Henrikz
Updated on February 28, 2021Comments
-
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 about 13 years
$var = '1'; function() { global $var; $var + 1; return $var; }
-
Henrikz about 13 yearsBah, it's just too easy! Anyway, huge thanks for the quick reply! Cheers mate!
-
Admin about 13 yearsgenerally not recommended to use global any more than absolutely necessary
-
David Harkness about 13 yearsEven provided access via
global
, the statement$var + 1;
evaluates to2
but doesn't store the result anywhere. Try$var++;
or$var += 1;
, but note that it changes the original variable as well. -
devios1 over 11 yearsSince you're not answering the question, I think this would have made more sense as a comment. It is correct nevertheless.
-
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