note 37642 deleted from language.oop.serialization by danbrown

From: Date: Sat, 07 Nov 2009 19:13:01 +0000
Subject: note 37642 deleted from language.oop.serialization by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162606@lists.php.net to get a copy of this message
Note Submitter: arthurp at nospam free dot fr ---- Good news when serializing a class and then reading it back into the similar or modified class. PHP behaves very well when a class was serialized and then it is unserialized to initialize similar class or when the class was modified meanwhile. Try this sample: First version of the class A contains members $one and $three. An instance of this class is stored into the file. The second version of the class A contains members $one as in prevoius but it also contains $two and and it doesn't contain $three member. The file is read back. Resulting class is still working ! <?php ///////////////////////////// // classa.inc: class A { var $one = 1; var $three = 3; function show_one(){ echo $this->one."<br>";} } ///////////////////////////// // classa_modified.inc: class A { var $two = 2; var $one = 1; function show_one(){ echo $this->one."<br>"; } function show_two(){ echo $this->two."<br>"; } } ///////////////////////////// // teststore include("classa.inc"); $a = new A; $s = serialize($a); // store $s somewhere where page2.php can find it. $fp = fopen("savedclass.tmp", "w"); fputs($fp, $s); fclose($fp); $a->show_one(); var_dump($a); ///////////////////////////// // testreadmodified.php: include("classa_modified.inc"); $s = implode("", @file("savedclass.tmp")); $a = unserialize($s); // now use the function show_one() of the $a object. $a->show_one(); $a->show_two(); var_dump($a); ?> Resulting Output: 1 2 object(a)(3) { ["two"]=> int(2) ["one"]=> int(1) ["three"]=> int(3) } ?> Note: - $one member is unserialized normally - $two member exist after unserialisation and it's well initialised with value 2 - show_two() function is working after unserialization - $thee member exist was loaded too even if it isn't declared in modified version of the class !

« previous php.notes (#162606) next »