How to use php serialize() and unserialize()

后端 未结 10 1872
Happy的楠姐
Happy的楠姐 2020-11-22 05:03

My problem is very basic.

I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They ju

10条回答
  •  春和景丽
    2020-11-22 05:49

    Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.

    1. Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
      • user personalization

    Note for object you should use magic __sleep and __wakeup methods. __sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

    __wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

    For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)

提交回复
热议问题