PHP - How does object serialization / non-serialization work?

I read serialize / unserialize PHP concepts. I was wondering how they are stored in the / db file system? I think this is in binary format. However, I wonder how the whole class is stored? I realized that the data in the data element can be saved, but how are the methods or saved?

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

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

PHP can know what to do in line # 2, but how does it know what to do in line # 5, which is an unerialized object? Does it also save code?

+4
source share
3 answers

PHP can know what to do in line # 2, but how does it know what to do in line # 5, which is an unerialized object? Does it also save code?

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

+4
source

When serializing an object, PHP saves only the current state of the object, that is, its property values. He does not serialize his methods. The corresponding class must be loaded into memory during non-serialization. PHP will restore the state of the object from the serialized string and transfer the rest of the information (structure and methods) from the class with the same name.

+6
source

This is a simple example for understanding serialize and unserialize object in php. we hide the object in a row using serialization and use the current status of the current object (with the given values) after non-serialization on another page.

c.php

 <?php class A { public $one ; public function A($val) { $this->one=$val; // echo $this->one; } function display(){ echo $this->one; } } ?> 

The c.php file has a class named A.
a.php

 <? require_once "c.php"; $ob= new A('by Pankaj Raghuwanshi : Object Searlization.'); $ob->display(); // Output is: by Pankaj Raghuwanshi : Object Searlization. $s = serialize($ob); // echo $s will show a string of an object ?> <br><A href='b.php?s=<?=$s;?>'>B-file</a> 

We serialize the conversion of this object to a string and pass this string to another page using the get method.

Note. . We can transfer this line from one page to another page using various methods, such as using a session, we can save to the database and extract another page, save to a text file.

We will exclude this object for another b.php file name

b.php

 <? require_once "c.php"; $ob = unserialize($_GET[s]); $ob->display(); // Output is: by Pankaj Raghuwanshi : Object Searlization. ?> 

after unserialization, the object shows the same behavior as the a.php file and assigning the value a.php is still in the object's memory. if we refuse this object after many HTTP requests. The object will store all destination values ​​in its memory.

0
source

All Articles