Class Person {
- Private $name;
- Private $age;
- function __construct ($name, $age) {
- $this->name = $name;
- $this->age = $age;
- }
function say () {
- echo "My name is:" $this->name. "
";
- echo "My Age is:". $this->age;
- }}
$p 1 = new Person ("Zhang San", 20);
- $p 1_string = serialize ($p 1);//write to file after serializing object
- $fh = fopen ("P1.text", "w");
- Fwrite ($fh, $p 1_string);
- Fclose ($FH);
- ?>
Copy CodeOpen P1.text file, enter: o:6: ' Person ': 2:{s:12: ' person name '; s:4: ' Zhang San '; s:11: ' Person of age '; i:20;} However, it is not usually straightforward to parse the characters generated by the above serialization. Two, deserialization:
Class Person {
- Private $name;
- Private $age;
- function __construct ($name, $age) {
- $this->name = $name;
- $this->age = $age;
- }
- function say () {
- echo "My name is:" $this->name. "
";
- echo "My Age is:". $this->age;
- }}
$p 2 = unserialize (file_get_contents ("P1.text"));
- $p 2, say ();
- ?>
Copy CodeOutput: My name is: Zhang San my age is: 20 tip because the serialized object cannot serialize its methods, the current file must contain the corresponding class or require class file when unserialize. Serialization is only available for limited users, because files need to be stored or written separately for each user, and the file name cannot be duplicated. In the event that the user does not exit the browser normally, the file is not guaranteed to be deleted. The object is registered as a session variable. When you have a large number of users, consider using the session to save the object. For more information about the session, see the article: A simple example of a session in PHP PHP session operation Class (with instance) PHP Session function set method of session expiration in PHP how to use the session in PHP application example PHP sessions usage example PHP logoff session information PHP5 cookie and session usage Example:
Session_Start ();
- Class Person {
- Private $name;
- Private $age;
- function __construct ($name, $age) {
- $this->name = $name;
- $this->age = $age; }
- function say () {
- echo "My name is:" $this->name. "
";
- echo "My Age is:". $this->age;
- }}
$_session["P1"] = new Person ("Zhang San", 20);
- ?>
Copy CodeRead session:
Session_Start ();
- Class Person {
- Private $name;
- Private $age;
- function __construct ($name, $age) {
- $this->name = $name;
- $this->age = $age;
- }
function say () {
- echo "My name is:" $this->name. "
";
- echo "My Age is:". $this->age;
- }}
- $_session["P1"], say ();
- ?>
Copy CodeOutput: My name is: Zhang San my age is: 20 as with serialization, registering an object as a session variable does not save its method. Therefore, when reading the session variable, the current file must contain the corresponding class or require corresponding class file. |