maybe_serialize()必要时序列化数据

目录

描述

译文

必要时序列化数据

原文

Serialize data, if needed.

maybe_serialize() 描述

用法

<?php maybe_serialize$data ); ?>

maybe_serialize() 用法

参数

$data

(mixed) (必填) Data that might be serialized.

默认值: None

maybe_serialize() 参数

返回值

(mixed) 

A scalar data

maybe_serialize() 返回值

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php

// Strings are returned untouched.
$data = 'Hello World!';
echo maybe_serialize( $data );
// Hello World!

// Integers, floats and boolean values are also returned untouched.
$data = 55;
echo maybe_serialize( $data );
// 55

$data = 4.560
echo maybe_serialize( $data );
// 4.560

$data = true;
$data = maybe_serialize( $data );
// $data = true;

$data = null;
$data = maybe_serialize( $data );
// $data = null

// An array or object will be returned as a serialized string.
$data = array( 1 => 'Hello World!', 'foo' => 'bar' );
echo maybe_serialize( $data );
// a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}

// A serialized string will be serialized again.
$data = 'a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}';
echo maybe_serialize( $data );
// s:50:"a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}";

?>

maybe_serialize() 示例

注意

  • Data might need to be serialized to allow it to be successfully stored and retrieved from a database in a form that PHP can understand.
  • Confusingly, strings that contain already serialized values are serialized again, resulting in a nested serialization. Other strings are unmodified.

A possible solution to prevent nested serialization is to check if a variable is serialized using
<?php if(!is_serialized$data )) { $data maybe_serialize($data); } ?>


More info at is_serialized().

maybe_serialize() 注意

历史

添加于 版本: 2.0.5

maybe_serialize() 历史

源文件

maybe_serialize() 函数的代码位于 wp-includes/functions.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Serialize data, if needed.
 *
 * @since 2.0.5
 *
 * @param string|array|object $data Data that might be serialized.
 * @return mixed A scalar data
 */
function maybe_serialize( $data ) {
	if ( is_array( $data ) || is_object( $data ) )
		return serialize( $data );

	// Double serialization is required for backward compatibility.
	// See https://core.trac.wordpress.org/ticket/12930
	// Also the world will end. See WP 3.6.1.
	if ( is_serialized( $data, false ) )
		return serialize( $data );

	return $data;
}

maybe_serialize() 源文件

相关