How "serialize()" operates

The following information is applicable only to library developers, that is, programmers that want to change the internal workings of PHPLIB. You may safely skip this section; some information here requires advanced understanding of the PHP language.

The heart of the session class is the serialize() internal function. This function takes an expression called prefix and generates PHP code that will assign the value of that expression to the expression when executed. For example, if the expression is $GLOBALS["a"] and the global variable $a has the value 17, then serialize will create the PHP program $GLOBALS["a"] = "17";. To save memory, serialize() operates on a reference parameter $str, where is will append the code generated.

First thing serialize() does is to determine the type of the current expression using the PHP gettype() function. The current type is stored in $t. The type of the expression may indicate either a scalar value (integer number, float number or string), an array or an object.

Scalar values are the easiest to handle: serialize() just evaluates the current expression and remembers the result value in $l. An assignment is generated that will assign the current value to the current expression. Since the current value may be a string and that string may contain bad characters (any of backslash, double quotes or dollar sign), these characters are backslashed. We are done, serialize() ends here for scalars.

In the case of $t indicating an array, code is generated to create an empty array (expression = array();). Then the keys of current expression are enumerated and for each key serialize() is called recursively with the current key appended to the expression. That will append code for each array slot.

Should $t indicate an object, code is generated to create that object (expression = new Classname;). Since one cannot find out the name of the class of an object for arbitrary objects in PHP, objects handled by serialize() must have a slot named classname. The object handler will then enumerate the contents of the objects slot persistent_slots and call serialize() recursively for each of these slots with the appropriate prefix.

Since many of the expressions used in serialize() require variable variable names or even variable code, eval() is used liberally. Unfortunately, this makes the code hard to read.