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.