Page 252 - Beginning PHP 5.3
P. 252
Part II: Learning the Language
an array of names of properties to preserve in the serialized string. You can use this fact to limit the
number of properties stored in the string — very useful if your object contains a lot of properties that
you don ’ t need to store.
Here ’ s an example:
class User {
public $username;
public $password;
public $loginsToday;
public function __sleep() {
// (Clean up; close database handles, etc)
return array( “username”, “password” );
}
}
$user = new User;
$user- > username = “harry”;
$user- > password = “monkey”;
$user- > loginsToday = 3;
echo “The original user object: < br / > ”;
print_r( $user );
echo “ < br / > < br / > ”;
echo “Serializing the object... < br / > < br / > ”;
$userString = serialize( $user );
echo “The user is now serialized in the following string: < br / > ”;
echo “$userString < br / > < br / > ”;
echo “Converting the string back to an object... < br / > < br / > ”;
$obj = unserialize( $userString );
echo “The unserialized object: < br / > ”;
print_r( $obj );
echo “ < br / > ”;
This code outputs the following:
The original user object:
User Object ( [username] = > harry [password] = > monkey [loginsToday] = > 3 )
Serializing the object...
The user is now serialized in the following string:
O:4:”User”:2:{s:8:”username”;s:5:”harry”;s:8:”password”;s:6:”monkey”;}
Converting the string back to an object...
The unserialized object:
User Object ( [username] = > harry [password] = > monkey [loginsToday] = > )
In this example, we don ’ t care about preserving the number of times the user has logged in today,
so the __sleep() method only returns the “username” and “password” property names. Notice that
the serialized string doesn ’ t contain the $loginsToday property. Furthermore, when the object is
restored from the string, the $loginsToday property is empty.
214
9/21/09 9:03:47 AM
c08.indd 214
c08.indd 214 9/21/09 9:03:47 AM