note 107194 added to class.serializable

From: Date: Fri, 13 Jan 2012 17:05:09 +0000
Subject: note 107194 added to class.serializable
Groups: php.notes 
Request: Send a blank email to php-notes+get-185634@lists.php.net to get a copy of this message
Serializing child and parent classes: <?php class MyClass implements Serializable { private $data; public function __construct($data) { $this->data = $data; } public function getData() { return $this->data; } public function serialize() { echo "Serializing MyClass...\n"; return serialize($this->data); } public function unserialize($data) { echo "Unserializing MyClass...\n"; $this->data = unserialize($data); } } class MyChildClass extends MyClass { private $id; private $name; public function __construct($id, $name, $data) { parent::__construct($data); $this->id = $id; $this->name = $name; } public function serialize() { echo "Serializing MyChildClass...\n"; return serialize( array( 'id' => $this->id, 'name' => $this->name, 'parentData' => parent::serialize() ) ); } public function unserialize($data) { echo "Unserializing MyChildClass...\n"; $data = unserialize($data); $this->id = $data['id']; $this->name = $data['name']; parent::unserialize($data['parentData']); } public function getId() { return $this->id; } public function getName() { return $this->name; } } $obj = new MyChildClass(15, 'My class name', 'My data'); $serial = serialize($obj); $newObject = unserialize($serial); echo $newObject->getId() . PHP_EOL; echo $newObject->getName() . PHP_EOL; echo $newObject->getData() . PHP_EOL; ?> This will output: Serializing MyChildClass... Serializing MyClass... Unserializing MyChildClass... Unserializing MyClass... 15 My class name My data ---- Server IP: 69.147.83.197 Probable Submitter: 187.66.77.226 ---- Manual Page -- http://www.php.net/manual/en/class.serializable.php Edit -- https://master.php.net/note/edit/107194 Del: integrated -- https://master.php.net/note/delete/107194/integrated Del: useless -- https://master.php.net/note/delete/107194/useless Del: bad code -- https://master.php.net/note/delete/107194/bad+code Del: spam -- https://master.php.net/note/delete/107194/spam Del: non-english -- https://master.php.net/note/delete/107194/non-english Del: in docs -- https://master.php.net/note/delete/107194/in+docs Del: other reasons-- https://master.php.net/note/delete/107194 Reject -- https://master.php.net/note/reject/107194 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185634) next »