Checking if an object has been serialized in PHP
I had a class that relied upon an object’s spl_object_hash() which the PHP documentation states : “is a string that is unique for each object and is always the same for the same object”.
However, in a comment of the documentation for that hash function, I read that: “Uniqueness is not guaranteed between objects that did not reside in memory simultaneously”.
This made me worry about what would happen if I compared the result of an spl_object_hash between serializations of an object.
Therefore, I wanted some way of checking if an object had been serialized in the past. If it had, I could at least take some kind of action (i just wanted to threw an exception).
So I added an implementation of the magic __wakeup method to my object of concern:
class MyObject {
....
public function __wakeup()
{
$this->hasBeenSerializedAtLeastOnce =TRUE;
}
...
}
Then I could test for it as so:
if ($MyObject->hasBeenSerializedAtLeastOnce) {
throw new Exception('this object has been serialized which means we cannot regenerate the spl hash with guaranteed accuracy');
} else {
$hash = spl_object_hash($MyObject)
}
I await comments from anyone who will tell me that this was all very silly and a waste of time….