maybe_serialize()

最后更新于:2021-11-27 14:43:10

maybe_serialize( string|array|object$data)

Serialize data, if needed.

参数

$data

(string|array|object) (Required) Data that might be serialized.

响应

(mixed) A scalar data.

源文件

文件: gc-includes/functions.php

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.gechiui.org/ticket/12930
	 * Also the world will end. See GC 3.6.1.
	 */
	if ( is_serialized( $data, false ) ) {
		return serialize( $data );
	}

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

?>