Dynamic code generation in PHP

As in most scripting languages, you can dynamically generate code in PHP. As a sidenote: the reason why it is so simple to implement dynamic code in scripting languages is that you already have the “eval” function (it is called with the script), all you have to do is to provide an interface to it from the language.

Usually you wouldn’t want to use this feature (since it adds complexity and can create security risks), however there might be exceptions. For example you might consider using this method if you need to write feature-rich code executed in a tight loop. Take a look at my script for creating gradients to see what I’m talking about.

There I had code which needed to support 3 color spaces and possibly will be called in a tight loop (to generate every pixel of an image for example – although I wouldn’t recommend that). The fact that the effective function got dynamically compiled avoided having to execute an “if” at every call (depending on the colorspace), because only the relevant code was included.

Alternatively I could have written three separate implementation of the function (depending on the color space) and note in an instance variable which one needs to be used. This achieves the same performance but gives more “compile time” syntax checking:

class ColorGradient {
  function calcRGB(...) { ... }
  function calcYUV(...) { ... }
  function calcHSV(...) { ... }

  function getColorArray(...) {
    return call_user_func(array('ColorGradient ', $this->calcFuction), ...);

In conclusion: with all the recent (and not so recent) additions PHP is getting a very powerful scripting language for the web.

Leave a Reply

Your email address will not be published. Required fields are marked *