Monday, December 29, 2008

The power of eval

In my programming environment we use PHP and javascript as our primary programming languages. One very handy construct that both of these languages have is the eval statement, which essentially allows a text string to be converted into and executed as code.

An example in PHP:

if(strpos($cToolTip,'$')) {eval("\$cToolTip = \"$cToolTip\";");}

An example in javascript:

eval("day.onclick= function() {goToDate('" + xday + "');};");

In the PHP example, we are checking if the string $cToolTips has any embedded variables (which always begin with a '
So, if we have:

$fubar = 'abc123'
$cToolTip = "Once upon a $fubar night"

After the eval statement, $cToolTip = "Once upon a abc123 night"

The javascript example, while functionally similar, has another very important advantage when programming in js. Lets say you have a loop, and within that loop you are creating a new elements on a page, and are assigning onclick events to these elements. So far, so good.

However, in our example,

eval("day.onclick= function() {goToDate('" + xday + "');};");

Note that we are assigning xday as a paramater in the goToDate function. This is great, except for one thing. If we did not use eval, every time we incremented or changed xday, it would change in every function in which it had been used.

Thus, the eval statement lets us, in effect, turn a variable into a constant so that we do not have to worry about the value of that variable once the eval statement has been run. That can be very handy.

No comments: