函数文档

maybe_serialize()

💡 云策文档标注

概述

maybe_serialize() 是 WordPress 核心函数,用于在需要时序列化数据,以便于数据库存储和检索。它处理数组、对象和已序列化字符串,但可能导致嵌套序列化问题。

关键要点

  • 函数接受字符串、数组或对象作为参数,返回标量数据。
  • 如果数据是数组或对象,则使用 serialize() 进行序列化。
  • 对于已序列化的字符串,出于向后兼容性考虑,会再次序列化,可能导致嵌套序列化。
  • 建议使用 is_serialized() 检查以避免嵌套序列化。

代码示例

$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";}

$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";}";

注意事项

  • 嵌套序列化可能引发数据存储问题,开发者应谨慎处理已序列化字符串。
  • 函数自 WordPress 2.0.5 引入,广泛用于选项、元数据等核心功能。

📄 原文内容

Serializes data, if needed.

Parameters

$datastring|array|objectrequired
Data that might be serialized.

Return

mixed A scalar data.

More Information

  • 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 is_serialized()
if( !is_serialized( $data ) ) {
$data = maybe_serialize($data);
}

Source

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;
}

Changelog

Version Description
2.0.5 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Basic Examples

     '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";}";
    
    ?>