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.
Hi. I'm Victor Nicollet,
Recent Comments