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.
To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.
If you wish to use a PHP global variable inside a certain function, you should use the keyword global in front of the variable. In the example below you can see how PHP variables $x and $y are used inside a function called learnTest() . <?
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
No, you cannot access the local variable of a function from another function, without passing it as an argument. You can use global variables for this, but then the variable wouldn't remain local.
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? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With