Thursday, October 29, 2015

Assign values to dynamic variable in PHP without using eval()

In PHP eval() function is evil.  I try my best not to use it. The eval() function has been misused by hackers so much... that I usually scan through my (or somebody else's)  PHP scripts when I suspect some malware has been installed (infected PHP files).

Here is a quick grep command to find all files with keyword 'eval(':

grep -rn "eval(" /data_local/app 


One situation when I have the need to use eval, is when I am assigning a dynamic variable.  Okay first I should probably explain what I mean by dynamic variable.  Dynamic variable is a technique to define a variable programmatically, meaning your scripts are defining the PHP variables automatically.

Look at this code as an example:

<?php
$variable_name = 'my_variable';

$variable_value = 123;

$$variable_name = $variable_value;

echo $my_variable;
?>

The output of the above PHP codes will be:

123

 Lets examine what the code did... on line 3 ( $$variable_name = $variable_value; )

We are actually defining $my_variable with the value 123.

PHP makes this very simple with using $$ operator, which kind of makes sense.