Serializing data is simply converting a value into a string. Imagine you had an array in PHP that you wanted to serialize, it would look something like the following...
$arr = [
'one' => 'val',
'two' => 'val',
];
$serializedArray = serialize($arr);
/**
echo $serializedArray;
output:
"a:2:{s:3:"one";s:3:"val";s:3:"two";s:3:"val";}"
**/
Let's dissect it.
-
a:2- The proceeding value is an array of length2 -
s:3- This item is a string of length3with a value ofval -
s:3- This item is also a string of length 3 and value ofval
You can imagine how different data types are represented in this fashion.
-
string-s:length:value -
int-i:value -
bool-b:value -
array-a:size:{key definition;value definition;} -
object-O:strlen(class name):object name:object size:{s:length:property name:property definition;(repeated per property)}
Pretty easy to understand once you know the format.
Resources:
Top comments (4)
object-O:strlen(class name):class name:object size:{s:length:property name:property definition;(repeated per property)}While I can appreciate and understand the semantics of noting (class name), I don't believe that is technically correct. As far as I know, you can't serialize a class without first instantiating it (unless perhaps doing something fancy with reflection). This instantiation is what creates an object, which is what is serialized. So I believe my example is accurate.
Look into serialized object. This name is a class name, not an object name. The object have no name.
OK, after thinking about it a bit more critically I see what you're saying and I agree you are correct.
To those wanting to follow along...
Since serialize is used to essentially instruct PHP on how to recreate a value/variable, it needs to know what class to instantiate a new object with. That is what Vlastimil is pointing out, that serialization isn't storing the name of the object, but rather a reference to which class it inherits its methods/properties from.