Serialization variables and serialized objects in PHP _php tutorial

Source: Internet
Author: User
Tags object serialization
Serialization is probably the form of converting some variables into a byte stream of strings, which is easier to transmit and store. Of course, off is the transfer of storage nothing, the key is to become a string of the form can be converted back, but also to maintain the structure of the original data.

A function that has multiple serialization in PHP: Serialize (), which converts any variable value (except a resource variable) into a string, can save the string to a file, or register as a session, or use curl to simulate get/post to transfer variables, Achieve the effect of RPC.

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

I. Serialization of variables

Let's take 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 the variable";

Boolean type:

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

Output:

B:1;
b:0;

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

Variable type: [variable length:] variable value;

The first character represents the variable type, the second: the partition, the variable length is optional, is in the string type, other types are not, the last one is the variable value, each serialized value with ";" As the end.

For example, our integer number 23 serialization is: I:23, then it has no length, only the type and variable values, I represents the integer, separated by a colon, followed by an integer value of 23, including floating-point type (double-byte type) is the same. Boolean, the type is B (Boolean), if true, then the value of serialization is 1, if False then the value is 0. Word

In the middle of the string value, one more save is worth, the length value of the strings is saved, such as the string "This is a string", then the generated serialization value is s:16: "The is a string"; S is a string, representing the type, the middle of the 16 is the length of the string, if it is Chinese, then each Chinese is two characters to save, such as the string "I is a variable", the resulting serialization value is: s:8: "I am a variable"; is a length of 8 characters.

Let's 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";}

is to put my array $var serialized string value, our $var array consists of 4 string elements, namely "ABC", "Def", "XYZ", "123", we analyze the serialized data, for the sake of simplicity, we put the serialized data array of the 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 clearer, look at the beginning of the string: a:4:{...} first character a holds the variable type array (array) type, the second 4 holds the number of array elements, a total of 4, and then the contents of the array element between {}. For example, the first array element: I:0;s:3: "abc"; I means that the index value type of the current array element is integer, and the value is 0, the element value is of type S (String), the number is 3, the value is "ABC", the semicolon ends, and the following array elements are followed.

Let's 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 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, there is not much difference, 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 the index value: s:6: "Index1"; S is a 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 type serialization, in fact, we can completely construct their own serialization function, or from this point of view to expand, develop their own serialization program, convenient for our variable exchange.

Of course, we can also use this function, the array or any other variable serialization into a string, and then through the curl function to simulate the get/post function, so that the user can not execute the action from the remote server to obtain data from the function.

II. serialization of objects

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

Let's look at an example first:

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 Result:

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

Let's analyze a string after 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 content of the object itself: O:9: "TestClass": 2:o is a description of the object type (object), 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"; is a description of the property value. The following properties are similar.

First of all, the application of object serialization, the following is the PHP manual, the original text is not changed.

Serialize () returns a string containing a 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 hold all the 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 the $a. The definition of Class A must appear in page2.php if you want to serialize it in page2.php and rebuild the object $a of Class A. This can be done, for example, by placing the definition of Class A in an include file and including this 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 $s somewhere so 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);

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

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

It is strongly recommended that the definitions of the classes of these registered objects be included in all pages, even if these classes are not used on all pages. If you do not, an object is deserialized but does not have a definition of its class, it loses the class associated with it and becomes an object of StdClass without any functions available at all, which is useless.

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

Of course, a serialized object can actually be used in many places. Of course, the processing of serialization in PHP 5 is different, so let's take a look at the word in the manual:

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

The purpose of using __sleep is to close any database connections that an object might have, submit data for waiting, or perform similar cleanup tasks. In addition, this function is useful if you have very large objects and do not need to be fully stored.

Conversely, unserialize () checks for the existence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that an 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.

http://www.bkjia.com/PHPjc/313909.html www.bkjia.com true http://www.bkjia.com/PHPjc/313909.html techarticle serialization is probably the form of converting some variables into a byte stream of strings, which is easier to transmit and store. Of course, off is the transfer of storage nothing, the key is to become a string of the shape ...

  • 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.