开发者

,what is the use and benefit of Serialize() function in php

I know its Generates a storable representation of a value a开发者_运维问答nd used to access the objects across the php files but what if i dont use this function while storing the objects.


Let's say you have some post data, but your database/persistent storage can't be modified to store the new post data in separate fields.

You could serialize your $_POST array and store it in the persistent storage you've got. It's useful for generating user-based CRUD applications. I've found the necessity of storing the POST as a "payload" of sorts quite invaluable at times.

Knowing you can do something, doesn't mean you have to use it everywhere.


That is easly explained by reading the official PHP page that states:

Generates a storable representation of a value This is useful for storing or passing PHP values around without losing their type and structure.

Basically you can serialize an object write the string in a file and on another request you can simply read the file and unserialize it to have the final object loaded.


When you want to store or send data in a "safe" format, preserving PHP type and structure.

For example, you have an UTF-8 string with Japanese text. Or a multidimensional array. You can save it to a text file or insert into a database.

$array = array( 'key' => 'value', 'other_key' => 'other_value');
file_put_contents( 'array.txt', serialize( $array ) );

When you want to use the stored data, you may use the "unserialize" function:

$contents = file_get_contents( 'array.txt' );
$array = unserialize( $contents );

You can serialize values of any PHP type, including objects, but except the "resource" type (database connections, file handlers, etc.)

When you unserialize an object, you must ensure to have loaded its class previously.

More at the PHP manual: http://php.net/serialize


To serialize means converting runtime variables into consistent form. Often this is a simple string or XML representation of the code segment.

Usage:

<?php

    $user = new UserObjectFromDatabase();
    $data = serialize($user);

    http_reqeust_send($to = "some remote server", $data);
    // the remote server can now use unserialize($data) to re-construct the user object

?>


If you want to communicate a PHP variable (array, class, string, etc) to another script/a database/write it in a file, you serialize it. Suppose you have a little script that you want to run multiple times, and you need a place to keep some data between script runs. Here is a sketch of what you do:

if(file_exists($thefile)) {
    $data = unserialize(readfile($thefile));
} else {
    $data = array(); // or anything
}

// do something with data

$f = fopen($thefile);
fwrite($f, serialize($data));
fclose($f)


You can store a PHP structure in a file, session or even database. I use it for caching query results in a file or in memcache.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜