Balduran, here is the solution to your problem:
http://us.php.net/manual/en/language.oop5.magic.php#81492
and here is the working code:
class A {
public $a1 = 'a1';
protected $a2 = 'a2';
private $a3 = 'a3';
public function __sleep() {
return array("a1", "\0*\0a2", "\0A\0a3");
}
}
class B extends A {
public $b1 = 'b1';
public $b2 = 'b2';
public $b3 = 'b3';
public function __sleep() {
return array_merge(array("b1", "b2", "b3"), parent::__sleep());
}
}
print_r(unserialize(serialize(new B())));
オブジェクトのシリアル化 - セッションでのオブジェクト
serialize() は、PHPで保存可能な全ての値のバイト ストリーム表現を有する文字列を返します。 unserialize() は、この文字列を使用して元の変数 値を再生することが可能です。オブジェクトを保存するためにシリアル化 を行うと、オブジェクトの全ての変数が保存されます。オブジェクトの関 数は保存されません。クラス名だけが保存されます。
オブジェクトの unserialize() を可能とするために、 そのオブジェクトのクラスが定義される必要があります。つまり、クラス Aのオブジェクト$aを page1.phpで定義し、 これをシリアル化した場合、 クラスAを指す文字列が得られ、そこには、$aに含まれる変数の全ての値 が含まれます。page2.phpでこの文字列を非シリアル化したい場合、クラ スAの$aを再生します。クラスAの定義が、page2.phpに 現れます。これは、 例えば、クラスAのクラス定義をインクルードファイルの中に保存し、 page1.php および page2.php の中で共にこのファイルを読み込むことに より実行可能です。
<?php
// classa.inc:
class A
{
var $one = 1;
function show_one()
{
echo $this->one;
}
}
// page1.php:
include("classa.inc");
$a = new A;
$s = serialize($a);
// page2.phpが見付られる場所に$sを保存
$fp = fopen("store", "w");
fwrite($fp, $s);
fclose($fp);
// page2.php:
// これは非シリアル化が正しく動作するために必要
include("classa.inc");
$s = implode("", @file("store"));
$a = unserialize($s);
// オブジェクト$aの関数show_one()を使用する
$a->show_one();
?>
セッションを使用している場合に、オブジェクトを登録するために session_register()を使用すると、これらのオブジェ クトは各PHPページの最後で自動的にシリアル化され、次のページで自動 的に非シリアル化されます。これは、基本的に、これらのオブジェクトが 一旦セッション変数となると、全てのページに現れることを意味します。
全てのページでこれらのクラスを実際には使用しない場合でも、全てのペー ジでこのような登録された全てのオブジェクトのクラス定義を読み込むこ とが強く推奨されます。これを行わずに、クラス定義が存在しない状態で オブジェクトが非シリアル化された場合、クラスの相関は失われ、全ての 関数が利用できなくなるため、クラスのオブジェクト stdClassは利用価値がかなり低くなります。
このため、上の例で、session_register("a")を実行 することにより $a がセッションの一部となった場合、page1.php および page2.phpだけでなく、全てのページでファイル classa.incを読み込むべきです。
オブジェクトのシリアル化 - セッションでのオブジェクト
07-Mar-2008 06:39
02-Jan-2008 11:36
This is an interesting thing with classes when B extends A, then private variable of class A will not be serialized when using magic method __sleep(). Without __sleep() it works fine.
class A {
public $a1 = 'a1';
protected $a2 = 'a2';
private $a3 = 'a3';
public function __sleep() {
// option 1: wont work, says:
// Notice: serialize() [function.serialize]: "a3" returned as member variable from __sleep() but does not exist in **/index.php on line **
return $this;
// option 2: wont work, says:
// Notice: serialize() [function.serialize]: "a3" returned as member variable from __sleep() but does not exist in **/index.php on line **
$keys = array();
foreach( $this as $key => $value)
$keys[] = $key;
return $vals;
}
}
class B extends A {
public $b1 = 'b1';
public $b2 = 'b2';
public $b3 = 'b3';
}
print_r(unserialize(serialize(new B())));
Not sure if this is bug or feature.
18-Dec-2007 12:02
It's worth noting that when you serialize an object (after creating it normally), its __sleep method will be called, and then when the object naturally goes out of scope, it's __destruct method will also be called.
However, when you unserialize an object, its __wakeup method will be called, but it's __construct method will not be called.
I'm not quite sure if there's a way to force an object completely out of scope without having __destruct automatically be called. If there is though (and it's neat - not like invoking 'die' at the end of every page), I'd like to hear about it!
03-Sep-2007 04:25
If you use __autoload(), this is also used when unserialize() hits a serialized class. So no need to include() all files everywhere...
19-Dec-2005 02:35
If you have register_globals = on, then be very careful about naming conventions when it comes to sessions and objects.
Example:
<?php
/* Setting the session variable, which becomes "$order" if register_globals is on */
session_start()
$_SESSION["order"] = "SomeValue";
/* Instantiating an object with the same name as the session variable */
$order = new Classname;
?>
This will activate the __PHP_Incomplete_class object within your session variable! This, all references and methods to $order will not work.
Took me hours to figure this out, so I hope this is helpful.
13-Aug-2005 07:06
never serialize an object, if it contains references to itself. Just create the object in an array, or make a reference of this object in an array before calling serialize() and serialize the array instead of the object.
print_r is fine to validate a reference: The reference will be serialized in a right way, if print_r returns a *recursive* on right place (look carefully).
Just have a look on this small example:
<?
class foo {
var $bar;
function addBar() {
$this->bar = new bar(&$this);
}
}
class bar {
var $parentFoo;
function bar(&$partentBean) {
$this->parentFoo =& $partentBean;
}
}
$foo = new foo();
$foo->addBar();
$fooArray = array(&$foo);
echo "<pre>";
print_r($foo);
echo serialize($foo);
echo "</pre>";
echo "<pre>";
print_r($fooArray);
echo serialize($fooArray);
echo "</pre>";
?>
OutPut:
foo Object
(
[bar] => bar Object
(
[parentFoo] => foo Object
(
[bar] => *RECURSION*
)
)
)
O:3:"foo":1:{s:3:"bar";O:3:"bar":1:{s:9:"parentFoo";O:3:"foo":1:
{s:3:"bar";O:3:"bar":1:{s:9:"parentFoo";R:3;}}}} //sorry for linebreak
Array
(
[0] => foo Object
(
[bar] => bar Object
(
[parentFoo] => *RECURSION*
)
)
)
a:1:{i:0;O:3:"foo":1:{s:3:"bar";O:3:"bar":1:{s:9:"parentFoo";R:2;}}}
if you serialize the object, the the refernce becomes a copy an first the reference inside the copy is a real reference, (but just only to the copy, for sure :).
25-May-2005 07:31
I can't store an instance of MySQLPagedResultSet (I grabbed this code from Kevin Yank at Sitepoint) in my session without losing all the data. This seems related to the previous post since the result set member variable is from calling mysql_query(). It doesn't get serialized properly and when I retrieve it from the session the result set is empty.
My workaround is store the query (ie. select * from mydata where id in (1,2,3...)) instead of the result set. In this particular case, it works beautifully and yields a big performance boost, since the id's are generated from several other queries that can now be avoided. With query caching on in mysql, I would not be surprised if this is just as fast or faster than retrieving the result set from the session. There are fewer potential data synchronization problems, too, since the info from mydata is fresh.
21-Apr-2005 03:51
Was wondering, if References are also lost after serializing and deserializing in php5.
Wrote a testfile and my result is:
All references are restored corretly. Even if the classes where recursively referenced.
Here is the code of the file:
<?
//check refereneces
class A
{
public $a_var;
/**
* @var B
*/
public $parent;
public function __construct($parent)
{
$this->parent=$parent;
}
}
class B
{
/**
* @var A
*/
public $Ref_auf_A;
/**
* @var A
*/
public $aObj;
public $name="";
public function __construct($InhaltA)
{
$this->aObj=new A($this);
$this->aObj->a_var=$InhaltA;
$this->Ref_auf_A=$this->aObj;
}
}
$B_obj = new B("Inhalt von A");
$B_obj->name="My is <defaultName>";
echo "Object B before serializing:<pre>";
print_r($B_obj);
echo "</pre><br><br>";
$serB=serialize($B_obj);
echo "Object B serialized: ".$serB."<br><br>";
$B_obj = unserialize($serB);
echo "Object B deserializedt:<pre>";
print_r($B_obj);
echo "</pre><br><br>";
$B_obj->Ref_auf_A->a_var="Test";
echo "Object A reference content changed, should have changed everywhere:<pre>";
print_r($B_obj);
echo "</pre><br><br>";
//Change name of object where A parent references to.
$B_obj->Ref_auf_A->parent->name="My name changed";
echo $B_obj->name;
?>
20-Mar-2005 03:43
It seems that serializing an object dereferences all its attributes that were references - even if the object they referenced was contained within the serialized one.
Consider this example:
<?
class foo {
var $a=new array();
}
$example=new foo;
$obj=new whatever();
$example->a[]=&$obj;
$example->a[]=$obj;
//now $example contains a list with
//both: an object and a reference to that object
//let us serialize and immediately unserialize $example:
$string=serialize(example);
$example=unserialize(string);
//now the situation is completely different!
//$example contains just two identical objects,
//the reference is lost
?>
03-Jun-2004 01:45
A special gotcha for unserializing stored objects. If you alter the class (adding new methods), they will appear and be available when the object is unserialized. If, however, you alter the parent class that the class extends, the methods are *not* available, and any renamed ones silently vanish (the method disappears and does not reappear under the new name).
A way to get around this is to create a new dummy method in the child class and rename it each time you alter the parent class. This is very much a Bad Solution when you have to deal with a base class that is extended by dozens of other classes. Especially when you have a database full of serialized objects, each of which is a child of the base class. There appears to be no runtime fix.
Applies to PHP 4. Not sure about 5.
06-May-2004 02:32
When working with a installation where Register Globals if off. You must remeber to use $_SESSION['objectName'] to store objects that will be used on multiple pages.
To re-use a saved object, you must define your object (i.e. include it's class file) before you call session_start(), or the object becomes unusable.
21-Nov-2003 11:00
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 !
05-Mar-2003 03:21
I had a problem using session_register() to globally store a class that I was working with. I hope my solution will help beginners understand this concept of sessions in PHP
When you use session_register() to store any object, yes you don't need to call session_start() unless you want to. However in other pages where you want to use that object, you must call session_start() after you have included the class definition of the file. Failure to do this will unserlize your object without its functions and it will be pretty useless.
Hope it helps someone.
Cheers.
15-Nov-2002 08:10
Serialization is very useful for the storing of objects in databases.
The following example stores an obbect in a mySQL db:
# Seperate Class.
include 'thisObjectClass.php';
# Create instance of a class.
$object = new thisObjectClass;
# Create link to the database
$link = mysql_connect('host', 'user', 'password');
mysql_select_db('dbname', $link);
# Formulate query and submit.
$sql_query = mysql_query("INSERT INTO objecttable(object) VALUES (serialize($object)") or print (mysql_error());
# Retrieve blob object.
$sql_query = mysql_query("SELECT object FROM objecttable WHERE 1) or print (mysql_error());
$row = mysql_fetch_row($sql_query);
# This should show string / text data.
print $row[0];
# This should show 'object'.
print unserialize($row[0])."<br>";
# Close db link.
mysql_close($link);
15-Nov-2002 07:07
Don't forget to lock your storage file using flock() before opening the file you wish to use to store your serialized object(s)! PHP will make no attempt to prevent two threads or processes from writing to your file at the same time and you can easily end up with a corrupted data store unless you serialize access to your storage. (Note that using NFS for your storage may not be lock-safe.)
25-Aug-2002 09:26
A quick note about objects containing another object as a variable. Say you have something like this:
class A {
var $A_Var;
}
class B {
var $A
var $B_Var;
function B() {
$this->A = new A();
}
}
$B = new B();
$B->A->A_Var = "A_Var value";
---
When you try to serialize() an instance of B() $B->A->A_Var doesn't seem to keep it's value.
After much fighting with this the solution I found was to append to my __sleep and __wakeup functions and serialize $this->A in __sleep and then unserialize it in __wakeup.
class A {
var $A_Var;
}
class B {
var $A
var $A_serialized;
var $B_Var;
function B() {
$this->A = new A();
}
function __sleep() {
$this->A_serialized = serialize($this->A);
return array('A_serialized', 'B_Var');
}
function __wakeup() {
$this->A = unserialize($this->A_serialized);
}
}
08-Jul-2002 10:31
Got around the session_auto_start problem by using:
session_write_close();
class defination
session_start();
works for me
08-Jul-2002 10:57
The deserialize callback function is pretty useless if you name your classes and files using title case (ie ClassName.php), because PHP changes all classnames to lower case!!!
27-May-2002 03:13
In case this isn't clear:
In 4.2 and below: session.auto_start and session objects are mutually exclusive.
17-Apr-2002 11:52
The problem with objects during session management arise because the object definition must exist before starting the session. i.e. if you have object x and you want to use it in a session, you have to perform the following.
<?
class x
{
...definition here
}
// php now knows what x is... start the session
session_start();
session_register("x_as_variable");
?>
if object x is defined in another file, make sure that the file is included or required BEFORE you start the session.
<?
require("x.inc");
session_start();
session_register("x_as_variable");
?>
This stops the INCOMPLETE_OBJECT response eliminating the need to create an array representation for an object.
17-Mar-2002 05:00
PHP.INI FILE AND SESSION.AUTO_START
Set
session.auto_start = 0
in php.ini file if you want that all works well during serialization/unserialization.
If session.auto_start is set to 1 all class definition is loaded after unserialization process, infact you obtain a messagge error like this "The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition className of the object you are trying to operate on was loaded _before_ the session was started in scriptFile on line n"
20-Feb-2002 11:15
A quick note about automatic serialisation in sessions.
If you have an object
$myCart = new ShoppingCart();
and this object contains variables which are objects
function ShoppingCart()
{
$mySingleItem = new BasketItem();
}
this will work fine and you can access the contained object $mySingleItem and its methods etc ONLY WHILE YOU ARE ON THE PAGE WHERE YOU CREATED IT.
if you are using sessions and register the cart
session_register('myCart')
the ShoppingCart object is serialised and unserialised on the next page ok but the inner BasketItem object is just garbled.
The only solution I have found is to use an array in the ShoppingCart instead of an object. What a pain!
22-Sep-2001 03:03
When storing an object that was generated with:
$row = mysql_fetch_object($result)
there is no apearent way to define the class of that object in the next page, without querying the database, and fetching a row as an object. This needs to be done so any such objects can be restored (deserialized) from a PHP4 Session.
It needs to be done before session_start() or session_register().
