I’ve worked with PHP for a few years now, but up until now never had a need to deal with serialisation explicitly, only using the $_SESSION. Now I have a project that requires me to manually implement serialisation mechanism for certain data – and I realise that the issue is applicable to $_SESSION as well.
I have a class that contains a number of properties. Most of these properties are small (as in memory consumption): numbers, relatively short strings, etc. However the class also contains some properties, which may contain HUGE arrays (e.g. an entire dump of a database table: 100,000 rows with 100 fields each). As it happens, this is one of the classes that needs to be serialised/deserialised – and, luckly, the properties containing large arrays don’t need to be serialised, as they are essentially temporary pieces of work and are rebuilt anyway as necessary.
In such circumstances in Java, I would simply declare the property as transient – and it would be omitted from serialisaion. Unfortunately, PHP doesn’t support such qualifiers.
One way to deal with is it to have something like this:
class A implements Serializable
{
private $var_small = 1234;
private $var_big = array( ... ); //huge array, of course, not init in this way
public function serialize()
{
$vars = get_object_vars($this);
unset($vars['var_big']);
return serialize($vars);
}
public function unserialize($data)
{
$vars = unserialize($data);
foreach ($vars as $var => $value) {
$this->$var = $value;
}
}
}
However this is rather cumbersome, as I would need to update serialize method every time I add another transient property. Also, once the inheritance comes into play, this becomes even more complicated – to deal with, as transient properties may be in both subclass and the parent. I know, it’s still doable, however I would prefer to delegate as much as possible to the language rather than reinvent the wheel.
So, what’s the best way to deal with transient properties? Or am I missing something and PHP supports this out of the box?
Php provides __sleep magic method which allows you to choose what attributes are to be serialized.
EDIT I’ve tested how does
__sleep()work when inheritance is in the game:So it seems that you can serialize parent data only if it’s declared as protected :-/
EDIT 2 I’ve tried it with
Serializableinterface with following code:So to sum up: you can serialize classes via
__sleep()only if they don’t have private members in super class (which need to be serialized as well). You can serialize complex object via implementingSerializableinterface, but it brings you some programming overhead.