函数文档

maybe_unserialize()

💡 云策文档标注

概述

maybe_unserialize() 是 WordPress 核心函数,用于安全地反序列化数据,仅在数据已被序列化时执行反序列化操作,避免错误处理非序列化数据。

关键要点

  • 参数 $data 是必需的数据字符串,可能包含序列化数据。
  • 返回值是混合类型,可以是反序列化后的任何数据类型,或直接返回原始数据。
  • 函数内部使用 is_serialized() 检查数据是否序列化,如果是则调用 @unserialize( trim( $data ) ) 进行反序列化。
  • 主要用于数据库存储和检索场景,确保 PHP 能正确处理序列化数据。

代码示例

function maybe_unserialize( $data ) {
	if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
		return @unserialize( trim( $data ) );
	}

	return $data;
}

注意事项

  • 函数自 WordPress 2.0.0 版本引入,是核心功能的一部分。
  • 相关函数包括 is_serialized(),用于检查数据是否序列化。
  • 在多个核心函数中广泛使用,如 get_option()、get_metadata_raw() 等,处理选项和元数据。

📄 原文内容

Unserializes data only if it was serialized.

Parameters

$datastringrequired
Data that might be unserialized.

Return

mixed Unserialized data can be any type.

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.

Source

function maybe_unserialize( $data ) {
	if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
		return @unserialize( trim( $data ) );
	}

	return $data;
}

Changelog

Version Description
2.0.0 Introduced.