Serialized variables and serialized objects in PHP

Source: Internet
Author: User
Serialization is probably the form of converting some variables into byte streams of strings, which is easier to transmit and store. Of course, there is nothing to do with data transmission and storage. The key is that data can be converted back in the form of strings, and the original data structure can be maintained. In PHP, there is a multi-serialize function: serialize (), which puts any variable values (except resource variables) serialization is probably the form of converting some variables into byte streams of strings, which is easier to transmit and store. Of course, there is nothing to do with data transmission and storage. The key is that data can be converted back in the form of strings, and the original data structure can be maintained.

There is a multi-serialized processing function in PHP: serialize (), which converts any variable value (except the resource variable) into a string and saves the string to the file, you can also register as a Session, or use curl to simulate GET/POST to transmit variables to achieve RPC.

If you want to convert a serialized variable to the original PHP variable value, you can use the unserialize () function.


  I. serialization of variables

A simple example is provided to illustrate serialization and its storage format.

Integer:
$ Var = 23;
Echo serialize ($ var );
Output:
I: 23;

Floating point type:
$ Var = 1.23;
Echo serialize ($ var );
Output:
D: 1.229999999999999982236431605997495353221893310546875;

String:
$ Var = "This is a string ";
Echo serialize ($ var );
$ Var = "I am a variable ";
Echo serialize ($ var );
Output:
S: 16: "This is a string ";
S: 8: "I am a variable ";

Boolean:
$ Var = true;
Echo serialize ($ var );
$ Var = false;
Echo serialize ($ var );
Output:
B: 1;
B: 0;

After the above basic types are serialized, it is clear that the storage format after serialization is:
Variable type: [variable length:] Variable value;

The first character represents the variable type, and the second character represents Segmentation. the variable length is optional, that is, in the string type. Other types do not exist, and the last one is the variable value, each serialized value ends.

For example, if integer 23 is serialized as I: 23, it has no length and only the type and variable value. I represents integer and is separated by a colon, the subsequent values are the integer value 23, including the floating point type (dubyte type. If it is boolean, the type is B (boolean). if it is true, the serialized value is 1, and if it is false, the value is 0. The string value contains one more value to be saved, and the length value of the string is saved. for example, if the string "This is a string" is generated, the serialized value is s: 16: "This is a string"; s is a string, which indicates the type. the 16 in the middle is the length of the string. if it is Chinese, each Chinese character is saved by two characters, for example, the serialized value of the string "I am a variable" is s: 8: "I am a variable", which is the length of 8 characters.

Next we will focus on the serialization of array variables.

Array variables:
$ Var = array ("abc", "def", "xyz", "123 ");
Echo serialize ($ var );
Output:
A: 4: {I: 0; s: 3: "abc"; I: 1; s: 3: "def"; I: 2; s: 3: "xyz"; I: 3; s: 3: "123 ";}

This is the string value obtained by serializing my array $ var. our $ var array includes four string elements, namely, "abc", "def", "xyz ", "123", let's analyze the serialized data. for convenience, we will list the serialized data into an array style:
A: 4:
{
I: 0; s: 3: "abc ";
I: 1; s: 3: "def ";
I: 2; s: 3: "xyz ";
I: 3; s: 3: "123 ";
}

The arrangement is clear. check the starting string: a: 4 :{...} first, the first character a stores the variable type as array, and the second character 4 stores the number of array elements, a total of four, then the content of the array element. For example, the first array element: I: 0; s: 3: "abc"; I indicates that the index value type of the current array element is integer and the value is 0, the element value type is s (string), and the number is 3. the specific value is "abc", the semicolon ends, and the following array elements are in turn.

Let's take a look at how to use a string as an element index:
$ Var = array ("index1" => "abc", "index2" => "def", "index3" => "xyz ", "index4" => "123 ");
Echo serialize ($ var );
Output:
A: 4: {s: 6: "index1"; s: 3: "abc"; s: 6: "index2"; s: 3: "def"; s: 6: "index3"; s: 3: "xyz"; s: 6: "index4"; s: 3: "123 ";}

After changing to an array style:
A: 4:
{
S: 6: "index1"; s: 3: "abc ";
S: 6: "index2"; s: 3: "def ";
S: 6: "index3"; s: 3: "xyz ";
S: 6: "index4"; s: 3: "123 ";
}

In fact, there is no big difference with the above, but the initial index becomes the form of saving the string, for example, the first element: s: 6: "index1"; s: 3: "abc "; the first item is the index value:

S: 6: "index1"; s is the type, 6 is the length of the index string, and "index1" is the index value. The following s: 3: "abc"; is the element value. this is easy to understand.

From the above, we have a general understanding of the serialization of basic data types. In fact, we can fully construct our own serialization functions, or expand from this perspective to develop our own serialized programs, this facilitates variable exchange.

Of course, we can also use this function to serialize arrays or any other variables into strings, and then use the curl function to simulate the GET/POST function, this function allows users to obtain data from remote servers when they are useless.

  II. object serialization

Object Serialization is also a common function. It serializes an object into a string and can be saved or transmitted.

Let's first look at an example:

Class TestClass
{
Var $;
Var $ B;

Function TestClass ()
{
$ This-> a = "This is ";
$ This-> B = "This is B ";
}

Function getA ()
{
Return $ this->;
}

Function getB ()
{
Return $ this-> B;
}
}

$ Obj = new TestClass;
$ Str = serialize ($ obj );
Echo $ str;

Output result:

O: 9: "TestClass": 2: {s: 1: "a"; s: 9: "This is a"; s: 1: "B"; s: 9: "This is B ";}

We will analyze the serialized strings of an object.
O: 9: "TestClass": 2:
{
S: 1: "a"; s: 9: "This is ";
S: 1: "B"; s: 9: "This is B ";
}

First, let's take a look at the object content: O: 9: "TestClass": 2:
O indicates that this is an object type (object). then 9 indicates the concentration of the object name, and 2 indicates that the object has several attributes. Check the following two attributes:

S: 1: "a"; s: 9: "This is a"; in fact, it is similar to the content of the array, the first item: s: 1: ""; is to describe the property name, the second item s: 9: "This is a"; is to describe the property value
. The following attributes are similar.

Let's first talk about an object serialization application. the following content is in the PHP Manual and the original text is not changed.
Http://www.php.net/manual/zh/language.oop.serialization.php)

========================================================== ======================================

Serialize () returns a string containing the byte stream representation of any value stored in PHP. Unserialize () can be used to reconstruct the original variable value. Serialization is used to save the object and save all the variables in the object. The functions in the object will not be saved, but only the class name.

To be able to unserialize () an object, you need to define the class of this object. That is, if the object $ A of Class a in page1.php is serialized, A string pointing to Class a is obtained and contains the values of all the variables in $. To serialize the object $ A in Class a in page2.php, the Class A definition must appear in page2.php. This can be implemented as an example. put the definition of Class A in an include file and include this file in both page1.php and page2.php.


// Classa. inc:
Class
{
Var $ one = 1;

Function show_one ()
{
Echo $ this-> one;
}
}

// Page1.php:
Include ("classa. inc ");

$ A = new;
$ S = serialize ($ );
// Store $ s somewhere so that page2.php can find
$ Fp = fopen ("store", "w ");
Fputs ($ fp, $ s );
Fclose ($ fp );

// Page2.php:
// This line is required for normal deserialization
Include ("classa. inc ");

$ S = implode ("", @ file ("store "));
$ A = unserialize ($ s );

// Now you can use the show_one () function of $ a object.
$ A-> show_one ();
?>

If the session is used and session_register () is used to register objects, these objects are automatically serialized at the end of each PHP page and automatically deserialized on each next page. Basically, once these objects become part of a session, they can appear on any page.

We strongly recommend that you include the class definitions of these registered objects on all pages, even if these classes are not used in all pages. If this is not done, an object is deserialized but has no definition of its class, it will lose the associated class and become an object of stdClass without any available functions, which is very useless. Therefore, if $ a becomes part of a session by running session_register ("a") in the preceding example, the classa. inc file should be included on all pages, not just

Page1.php and page2.php.

========================================================== ======================================

Of course, serialized objects can be applied in many places. Of course, the serialization processing in PHP 5 is different. let's take a look at the statement in the manual:
Http://php.liukang.com/manual/zh/function.serialize.php
Http://www.php.net/manual/zh/language.oop.magic-functions.php

Serialize () checks whether the class has a function named _ sleep. In this case, the function will run before any serialization. It can clear objects and should return

Array of all variable names to be serialized in this object.

The purpose of _ sleep is to close any database connection that an object may have, submit data in waiting or perform similar cleanup tasks. In addition, this function is useful if a very large object does not need to be fully stored.

Conversely, unserialize () checks the existence of a function with the magic name _ wakeup. If yes, this function can reconstruct any resources that an object may have.

_ Wakeup is used to reconstruct any database connections that may be lost during serialization and process other re-initialization tasks.

For object serialization in php 5, please refer to object serialization in PHP5 object-oriented programming in Haohappy: http://www.phpe.net/articles/407.shtml.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.