Php function get variable outside
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. Show A simple example of my code
I want this to return the value of 2.
RST 3,8382 gold badges19 silver badges32 bronze badges asked Feb 20, 2011 at 22:19
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
answered Feb 20, 2011 at 22:22
Jesse CohenJesse Cohen 4,01821 silver badges25 bronze badges 4 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.
answered Feb 20, 2011 at 22:25
JacobJacob 8,1931 gold badge22 silver badges29 bronze badges 1
OR
answered Feb 20, 2011 at 22:23
CzechnologyCzechnology 14.7k10 gold badges60 silver badges87 bronze badges
answered Jun 13, 2016 at 11:32
ChamandeepChamandeep 1662 silver badges7 bronze badges 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
answered Feb 20, 2011 at 22:24
This line in your function: Either of these will work, however: answered Feb 20, 2011 at 22:24
Brian DriscollBrian Driscoll 19k2 gold badges46 silver badges63 bronze badges 1
answered Feb 20, 2011 at 22:23 0 How do you access a variable outside a function?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.
How can use variable out of scope in PHP?Alternatively, you can bring variables in from the outside scope by using closures with the use keyword. This way is a little hard, for example if you have 10 variable this way will be hard. @JoeGreen, what is this functionality known as to be able to use the variables that are defined outside of function.
How do you call a function variable in PHP?There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );
How can you pass a variable by reference in PHP??> Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference.
|