How does object serialize/unserialize work?

21,228

Solution 1

PHP can know what to do at line#2 but how it knows what to do at line#5 which is a unserialized object? does it save the code as well?

Yes, serialize() will save the information about the class which this object is an instance of, along with its state, so when you unserialize, you get an instance of that class, which in this case is ClassName.

Solution 2

When serializing an object, PHP only stores the object's current state, i.e. its property values. It does not serialize its methods. The corresponding class needs to be loaded in memory at the time of unserialization. PHP will restore the state of the object from the serialized string and take the rest of the information (structure and methods) from the class of the same name.

Share:
21,228
dejjub-AIS
Author by

dejjub-AIS

Working at Applied IS Azure Technologies Architect Data Architect Data Migration expert MCSE in Cloud Platform and Infrastructure MCSE in Data Management and Analytics Aspiring Data Science Architect

Updated on July 09, 2022

Comments

  • dejjub-AIS
    dejjub-AIS almost 2 years

    I was reading about serialize/unserialize concepts of PHP. I was wondering how they are stored in the filesystem/db. I guess it is in the binary format. However, I wonder how entire class is stored? I understood that data in the data member can be stored but how are the methods stored?

    I mean, how does PHP know what code is written inside the function of say, someFunc()?

    $obj = new ClassName();
    $obj->someFunc();
    $serial = serialize($obj);
    $unserialobj = unserialize($serial);
    $unserialobj->someFunc();
    

    PHP can know what to do at line #2, but how it know what to do at line #5 which is an unserialized object? Does it save the code as well?

  • dejjub-AIS
    dejjub-AIS over 12 years
    can you please put some lite on what yo umean by "the corresponding clss needs to be loaded in memory at the time of unserialization"? how do i do that?
  • Gromski
    Gromski over 12 years
    @user Just include 'my_class.php';. PHP only needs to have seen the definition of your class. In other words, if you can do new ClassName, then you can unserialize an object of type ClassName.