2 January 2006
Evaluating Variables in PHP
This article covers traditional PHP evaluation. There is also an article on implicit PHP evaluation (dynamic evaluation without using eval) if you’d prefer.
I normally discuss the more advanced side of evaluation in this column, but while checking the referral logs today, I found a fair number of visitors coming from Google with searchs like “evaluating variables.” Though I intend to keep most of these articles more advanced, if people need help with plain-old eval(), I can oblige (and maybe even convince them not to use it!)
At some point in your life while developing an application, you will find yourself wondering how to assign a value to a variable without knowing the name of that variable while you’re writing that program. Through some means (from a user or perhaps the result of a function) you can get a variable name into another variable, but how do you assign a value to that? Example:
// a user submits a form with a textbox called "name" and this script handles it
$name = $_POST["name"]; // $name now holds "bob";
But how can I set $bob’s age or access a variable called $bob?
PHP features a function called eval(). Eval takes one or more lines of PHP code as a string and executres them as if there are actually in a PHP file a user has requested. It plays by the same rules that print uses. Variables values appear in place of the variable name in strings. Special symbols like $ or ” must be escaped by a backslash to make them appear as intended.
$string_php = "\$" . $_POST["name"] . " = " . $_POST["age"] . ";";
Consider the value of that string after it’s been generated. If you were to var_dump it, it would look something like string (10) “$bob = 41;”. It’s still just a string, though.
This is where eval comes in. We can call eval ($string_php); and PHP will execute it. Print out the value of $bob and it will be 41! Any statement you could write directly in PHP can also be written in a string and evaluated with eval() at runtime.
There are many other uses of eval(). Most, including the above examples, are completly unneccessary. Hower, explicit evaluation is easier to understand than implicit evaluation, so certainly for starting out, it’s worth knowing. However, eval also has preformance problems, and makes debugging much harder. You will start finding errors about syntax errors or missing functions on line 0, for instance. And it will frequently make your code much harder for a new developer. If evaluation really interests you, take a look at my article What is Implicit Evaluation? to learn more about it. Implicit Evaluation has personally allowed me nearly every benefit of eval() with few of the problems — it was over two years ago when I last used eval().

