note 115019 added to class.serializable
| From: | OlivierPons | Date: | Tue, 13 May 2014 16:19:50 +0000 |
| Subject: | note 115019 added to class.serializable | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199528@lists.php.net to get a copy of this message | ||
Here's the way you could implement serializable so that *ALL* descendant serialize themselves
without the need of re-writing for all descendant the functions serialize() and unserialize().
Note : this will only serialize "visible" properties, this it won't serialize private
descendant properties. If you dont want a property of a descendant to be serialized, make it
private.
class Pot implements Serializable
{
protected $_a;
protected $_b;
public function serialize()
{
return serialize(get_object_vars($this));
}
public function unserialize($data)
{
$values = unserialize($data);
foreach ($values as $key=>$value) {
$this->$key = $value;
}
}
}
And now one descendant:
class PotId implements Pot
{
protected $_k;
}
class Pots implements PotId
{
protected $_l;
}
$pots = new Pots();
and calling serialize($pots) will serialize all properties ($_a, $_b, $_k, $l).
----
Server IP: 72.52.91.14
Probable Submitter: 78.224.184.168
----
Manual Page -- http://php.net/manual/en/class.serializable.php
Edit -- https://master.php.net/note/edit/115019
Del: integrated -- https://master.php.net/note/delete/115019/integrated
Del: useless -- https://master.php.net/note/delete/115019/useless
Del: bad code -- https://master.php.net/note/delete/115019/bad+code
Del: spam -- https://master.php.net/note/delete/115019/spam
Del: non-english -- https://master.php.net/note/delete/115019/non-english
Del: in docs -- https://master.php.net/note/delete/115019/in+docs
Del: other reasons-- https://master.php.net/note/delete/115019
Reject -- https://master.php.net/note/reject/115019
Search -- https://master.php.net/manage/user-notes.php