The serialization of the core technology of PHP and the object of best practice ____php

Source: Internet
Author: User

PHP Core Technology and the serialization of best practice objects

An object is a bunch of data that can be stored so that it needs to be used, which is the serialization of objects.

Serialization is the preservation of various object states (attributes) stored in memory, and can be restored when needed. The following code implements saving the current state of an object in memory to a file.

$str = serialize ($student);

Echo $str;

File_put_contents (' Store.txt ', $str);

Output serialization Results:
O:6: "Person": 2:{s:4: "Name"; S:3: "Tom"; s:6: "Gender"; s:4: "Mail";}

Deserialize the object when it is needed:

$str = file_get_contents (' store.txt ');

$student =unserialize ($STR);

$student->say ();

Note: when serializing and deserializing, you need the definition of the object that contains the class, or it is possible that the object's class definition cannot be found when the object is deserialized, and incorrect results are returned.

As you can see, after the object is serialized, only the object's properties are stored. Classes are made up of properties and methods, and objects are collections of properties that are generated by the same class, have different properties, but share code for the method region in the code space of the class.

Expansion:serialize/unserialize is a serialized function of PHP, but the serialization of this set of functions will produce useless information, such as string length, resulting in the waste of space.

__tostring () is also a serialization. Where you implement your own serialization and deserialization, Json_encode/json_decode is a good choice.

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.