PHP: how to reset a global variable before each use in the function containing eval ()

advertisements

I have the following code in a website.

$magic_number_output = 'The magic number is: $magic_number';

function show_magic_number($magic_number) {
  global $magic_number_output;

  eval("\$magic_number_output = \"$magic_number_output\";");

  echo '
  ' . $magic_number_output;

}

The variable $magic_number_output is being set in a separate PHP file, then referenced using global inside a function as there will be different versions of this variable for different languages. $magic_number is passed into the function and this is replaced in the variable by using eval(). However, when the function is called more than once, the $magic_number does not change from the first value sent to the function. For example, if called like this:

show_magic_number(5);
show_magic_number(2000);

...the output is like this:

The magic number is: 5
The magic number is: 5

...when I would like it to be this:

The magic number is: 5
The magic number is: 2000

Obviously, I've misunderstood how global and eval() works and have tried searching for answers and experimenting but am simply too much of a noob to figure out a solution. I thought there might have been some way of resetting the global variable each time so that it doesn't continue to reference the $magic_number (i.e. 5) sent to the function the first time.

Can anyone suggest a way around this?


Try this. It will at least get rid of the eval()

$magic_number_output = 'The magic number is: $magic_number';

function show_magic_number($magic_number) {
  global $magic_number_output;

  $output=$magic_number_output;
  echo str_replace('$magic_number',$magic_number,$output);
}