Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I want this to return the value of 2.

like image 308
Henrikz Avatar asked Feb 20 '11 22:02

Henrikz


People also ask

How do you access variables 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 do you call a variable inside a function in PHP?

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() . <?

How can access global variable inside function in PHP?

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.

How can access local variable outside function in PHP?

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.


1 Answers

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? } 
like image 60
Jesse Cohen Avatar answered Sep 23 '22 19:09

Jesse Cohen