you have to declare the variable as a global in the function as well.
function setVar($value) {
global $myVar;
eval('$myVar = \' '. $value .' \';');
echo $myVar;
}
Question
I am stuck with a variable issue:
I will provide directly some code so that you can understand
global $myVar;
setVar('test');
function setVar($value) {
eval('$myVar = \' '. $value .' \';');
echo $myVar; //Here myVar is set to $vaue=test
}
echo $myVar; //Here the variable gets back to null, no output at all!
why ? I need to find a solution
EDIT:
I NEED ABSOLUTELY eval() method due to a for loop which needs to evaluate variables
Solution 2
you have to declare the variable as a global in the function as well.
function setVar($value) {
global $myVar;
eval('$myVar = \' '. $value .' \';');
echo $myVar;
}
OTHER TIPS
global
only works inside a function. it does not magically make a variable "superglobal" like you're trying:
$myvar = 'foo';
function setVar($value) {
global $myvar; // <---global must be used here INSIDE the function
$myvar = $value;
}
There is absolutely no need for eval()
in your code, and I strongly advise you NEVER to use it. Especially when starting out.