Serialization variables and serialized objects in PHP _php base

Source: Internet
Author: User
Tags curl object serialization serialization
Serialization is probably the conversion of some variables into the form of a string of bytes, which is easier to transfer and store. Of course, the switch is not what the transport storage, the key is to become a string form can be converted back, but also to maintain the original data structure.

In PHP, there are many serialization functions: Serialize (), which converts any variable value (in addition to the resource variable) into the form of a string, you can save the string to a file, or register as a session, and even use curl to simulate get/post to transfer variables, To achieve the effect of RPC.

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

One, the variable serialization

We give a simple example to illustrate serialization and its storage format.

Integral type:

$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 type:

$var = true;
Echo Serialize ($var);
$var = false;
Echo Serialize ($var);

Output:

B:1;
b:0;

After these basic types are serialized, it is clear that the storage format after serialization is:

Variable type: [variable length:] variable value;

Is that the first character represents the variable type, the second: represents the partition, the variable length is optional, is in the string type has, the other type does not, the last one is the variable value, each serialized value to ";" As the end.

Like our integer number 23 after serialization is: i:23, then it has no length, only the type and variable values, I is the integer, through the colon split, followed by the integer value of 23, including floating-point type (Double-byte type) is the same. Boolean, the type is B (Boolean), if true, then the serialized value is 1, and if it is false then the value is 0. Word

String value words will be saved in the middle of a value, save the length of the string, such as the string "This is a string", then the serialized value of the generated is s:16: "This is a string"; S is a string, representing the type, the middle 16 is the length of the string, if it is in Chinese, then each Chinese is two characters saved, such as the string "I am a variable", the generated serialization value is: s:8: "I am a variable"; is the length of 8 characters.

Now let's focus on the serialization of array variables.

Array variable:

$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";}

is to put the string value of my array $var serialized, our $var array consists of 4 string elements, namely "ABC", "Def", "XYZ", "123", and we analyze the serialized data, for the sake of simplicity, we have serialized data columns in the same style:

A:4:
{
I:0;s:3: "ABC";
I:1;s:3: "Def";
I:2;s:3: "XYZ";
I:3;s:3: "123";
}

This arrangement is more clear, look at the beginning of the string: a:4:{...} first character a saves the variable type as array (array) type, and the second 4 holds the number of array elements, a total of 4, and then the contents of the array element between {}. such as the first array element: I:0;s:3: "abc"; I represents the index value type of the current array element is an integral type, and the value is 0, the type of the element value is s (string), the number is 3, the value is "ABC", the semicolon ends, and the following array elements are followed by analogy.

Let's take a look at what it would be 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 becoming 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, not much different from the above, but the beginning of the index into the form of saving strings, such as the first element: s:6: "Index1"; s:3: "ABC"; The first is indexed: s:6: "Index1"; S is the type, 6 is the length of the index string, and "Index1" is the value of the index. Behind the s:3: "ABC"; is the element value, this good understanding, will not speak.

From the above, we have a general understanding of the basic data types of serialization, in fact, we can construct their own serialization functions, or from this perspective to expand, develop their own serialization program, easy to exchange our variables.

Of course, we can also use this function, the array or any other variables serialized into a string, and then through the curl function to simulate the get/post function, to achieve the useless user to perform the action from the remote server to obtain data from the function.

Second, the serialization of objects

The serialization of objects is also a common function that can serialize an object into a string that can be saved or transmitted.

Let's take a look at an example:

Class TestClass
{
var $a;
var $b;

function TestClass ()
{
$this->a = "This is a";
$this->b = "This is B";
}

function Geta ()
{
return $this->a;
}

function Getb ()
{
return $this->b;
}
}

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

Output results:

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

Let's analyze the string that follows the serialization of an object.

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

First look at the contents of the object itself: O:9: "TestClass": 2:o is a description of the object type, and then 9 is the name of the object to check the concentration, 2 is to represent the object has several properties. Looking at the contents of two attributes:

S:1: "A"; S:9: "This is a"; In fact, similar to the contents of the array, the first item: s:1: "a"; is a description of the property name, the second item S:9: "This is a"; That describes the value of a property. The following properties are similar.

First of all, the application of an object serialization, the following content is the PHP manual, did not change the original text.

Serialize () returns a string containing the byte stream representation of any value that can be stored in PHP. Unserialize () can use this string to reconstruct the original variable value. Using serialization to save an object can save all variables in the object. The function in the object is not saved, only the name of the class.

To be able to unserialize () an object, you need to define the class for that object. That is, if you serialize the object $a of Class A in page1.php, you get a string that points to class A and contains the values of all the variables in $a. If you want to serialize it in page2.php to reconstruct the object $a of Class A, the definition of Class A must appear in page2.php. This can be done, for example, by placing the definition of Class A in a containing file and including the file in both page1.php and page2.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);
Store the $s somewhere so page2.php can find
$fp = fopen ("Store", "w");
Fputs ($fp, $s);
Fclose ($FP);

page2.php:
This line is required for normal solution serialization
Include ("Classa.inc");

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

You can now use the Show_one () function of the $a object.
$a->show_one ();
? >

If you register objects with sessions and use Session_register (), these objects are automatically serialized at the end of each PHP page and automatically serialized in each subsequent page. Basically, these objects can appear on any page once they become part of the conversation.

It is strongly recommended that you include the definition of classes for these registered objects on all pages, even if they are not used in all pages. If this is not done, an object is deserialized without the definition of its class, and it loses its associated class and becomes an object of StdClass without any available functions at all, which is useless.

So if in the above example $a to be part of a session by running Session_register ("a"), you should include Classa.inc files in all pages, not just page1.php and page2.php.

Of course, the serialization of objects can actually be applied in many places. Of course, the processing of serialization in PHP 5 is different, so let's look at the instructions in the manual:

Serialize () checks whether the class has a magic name __sleep function. If so, the function will run before any serialization. It can clear the object and should return an array that contains all the variable names that should be serialized in the object.

The purpose of using __sleep is to turn off any database connections that the object might have, commit the waiting data, or perform similar cleanup tasks. Also, this function is useful if you have a very large object and you do not need to store it completely.

Conversely, unserialize () checks the existence of a function that has a magic name __wakeup. If present, this function can reconstruct any resources that the object might have.

The purpose of using __wakeup is to reconstruct any database connections that may be lost in serialization and to handle other reinitialization tasks.

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.