note 101926 added to function.serialize
| From: | reiners dot joh at googlemail dot com | Date: | Tue, 18 Jan 2011 19:02:57 +0000 |
| Subject: | note 101926 added to function.serialize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-175872@lists.php.net to get a copy of this message | ||
I just realized a certain behaviour when I serialize objects, store them in $_SESSION and
unserialize them after a reload.
More precisely, static fields of the object will be available when serializing/unserializing but NOT
when you do a page reload.
This is because the static fields are on class level, and certainly, the classes will be completly
initialized again when you do a page reload.
Actually that behaviour is correct, but i spent long long time to debug a script before i actually
realized this.
<?php
session_start();
echo "<pre>Press F5
";
class MyClass {
//static variable
static private $foo_static;
//normal variable
private $foo = null;
static function getString_static() {
return self::$foo_static;
}
static function setString_static($str) {
self::$foo_static = $str;
}
function setString($str) {
$this->foo = $str;
}
function getString() {
return $this->foo;
}
}
if (!isset($_SESSION['myObj'])) {
$myObj = new MyClass();
$myObj->setString_static("Will NOT be stored!!!");
$myObj->setString("Will be stored");
echo "Print content: \n";
echo 'Normal Var: ' . $myObj->getString() . "\n";
echo 'Static Var: ' . $myObj->getString_static();
echo "\t\n\nNow serialize and unserialize object\n";
$myObj = unserialize(serialize($myObj));
echo "And print again..\n";
echo 'Normal Var: ' . $myObj->getString() . "\n";
echo 'Static Var: ' . $myObj->getString_static();
//Store object in session
$_SESSION['myObj'] = serialize($myObj);
} else {
//if myobj was stored
$myObj_loaded = unserialize($_SESSION['myObj']);
echo "Print content when serialized, stored in session and unserialized after a
relaod:\n";
echo 'Normal Var: ' . $myObj_loaded->getString() . "\n";
echo 'Static Var: ' . $myObj_loaded->getString_static();
unset($_SESSION['myObj']);
}
?>
</pre>
----
Server IP: 69.147.83.197
Probable Submitter: 80.228.218.200
----
Manual Page -- http://www.php.net/manual/en/function.serialize.php
Edit -- https://master.php.net/note/edit/101926
Del: integrated -- https://master.php.net/note/delete/101926/integrated
Del: useless -- https://master.php.net/note/delete/101926/useless
Del: bad code -- https://master.php.net/note/delete/101926/bad+code
Del: spam -- https://master.php.net/note/delete/101926/spam
Del: non-english -- https://master.php.net/note/delete/101926/non-english
Del: in docs -- https://master.php.net/note/delete/101926/in+docs
Del: other reasons-- https://master.php.net/note/delete/101926
Reject -- https://master.php.net/note/reject/101926
Search -- https://master.php.net/manage/user-notes.php