Implicit Evaluation with PHP

2 January 2006

Limitations of Implicit Evaluation

Implicit evaluation is a very useful thing. For the sake of anyone new to it, implicit evaluation basically lets us treat a variable’s value as an identifier.

$fn = "print";
$fn ("hello, world!");

$color = "red";
$$color = "#ff0000";
echo $red;

In many ways, it is equivelent to having C/C++’s DEFINE directive as a part of the interpretter rather than pre-processor. However, it does have it’s limitations. As of PHP 4.4.x and 5.1.x, we can’t process statements implicitly. The following example, for instanse, won’t work:

$strExecute = "\$x = 1;";
$strExecute; // won't work as intended

Likewise, we can’t rely on scope resolution.

$bob = new Person();
$intAge = "bob->age";
$$intAge = 40; // will not work!

I find it easiest to think that there is no local scope. Imagine, instead, there is an associative array $localScope. When you write $bob->age = 40;, the compiler treats that more akin to $localScope[”bob”]->age = 40;. Therefore, when we try to write $$intAge = 40;, the evaluated code is more similar to $localScope[”bob->age”] = 40;. PHP doesn’t know that the value itself needs to be referenced, instead it tries to rely directly on the value. And how could it know better?

A slight tangent will now ensue: This is the same nature that allows us to use implicit evaluation for properties of an object:

$object = new Person();
$property = "name";
$object->$property = "bob"; // $localScope["object"]->name

The dollar-sign is what signals evaluation, so for any statically-evaluated code, we can use variables in place of any symbol.

One clearly missing piece to all this, however, is dynamically creating functions and objects. We cannot write function $strFunctionName () { return NULL; }. $strFunctionName is not evaluated, and so PHP will throw a syntax error. PHP does provide middle ground for functions, however. Through the create_function function, we can create named functions at run time. We don’t have scope to worry about, like we do with eval(), but we still have to escape quotes since the function content is a string rather than native PHP. With objects, however, I have not found another way. We really must call eval(”class person { … };”); (PLEASE NOTE the included semicolon). If it’s really neccessary to create objects at runtime, I implore you to make your evaluated class a subclass with as many common functions and properties factored into the native PHP class as you possible can.

That covers the limitations that I am aware of with implicit evaluation. Object strings aren’t evaluated, and we can’t create functions or objects at runtime without the aid of other native PHP functions.

No Comments currently posted.

Post a comment on this entry: