Serializing to PHP Code

For performance purposes, it can sometimes be interesting to have PHP code automatically generate other pieces of PHP code. In order to insert non-constant data into those pieces of code, the most elementary solution is to serialize everything as a string, and the unserialize them on the fly. While slow, this has the advantage of being very simple.

However, it’s possible to provide a function that handles all the special cases: numbers are printed as numbers, strings as correctly quoted and escaped strings, arrays are defined in the correct order and with the correct keys. Only objects (which may have specific sleep/wakeup code to be executed to allow them to remain alive) are actually saved.

function tophp($x)
{
  if (is_numeric($x))
    return "$x"; 

  if (is_string($x))
    return "'" . addcslashes($x, '\\\'') . "'"; 

  if (is_array($x))
  {
    foreach($x as $key => $id) $txt .= tophp($key) . '=>' . tophp($id) . ',';
    return 'array(' . $txt . ')';
  } 

  if (is_object($x))
    return "unserialize('" . addcslashes(serialize($x), '\\\'') . "')"; 

  if (is_bool($x))
    return $x ? 'true' : 'false'; 

  if (!isset($x))
    return 'null'; 

  assert (false);
}
I hereby declare this code to be in the public domain, where allowed by law.

0 Responses to “Serializing to PHP Code”


  1. No Comments

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



1150 feed subscribers
(readers who polled a feed this week)