rest_sanitize_object()
云策文档标注
概述
rest_sanitize_object() 是 WordPress REST API 中的一个函数,用于将对象类值转换为数组。它处理多种输入类型,确保返回一个关联数组或空数组。
关键要点
- 函数接受一个参数 $maybe_object,用于评估并转换对象类值。
- 返回值为数组:如果输入是 stdClass 实例,则强制转换为数组;如果输入是 JsonSerializable 实例,则调用 jsonSerialize() 方法;否则,若非数组则返回空数组。
- 函数在 WordPress 5.5.0 版本中引入,常用于 REST API 的数据清理和验证场景。
代码示例
function rest_sanitize_object( $maybe_object ) {
if ( '' === $maybe_object ) {
return array();
}
if ( $maybe_object instanceof stdClass ) {
return (array) $maybe_object;
}
if ( $maybe_object instanceof JsonSerializable ) {
$maybe_object = $maybe_object->jsonSerialize();
}
if ( ! is_array( $maybe_object ) ) {
return array();
}
return $maybe_object;
}注意事项
- 函数处理空字符串时直接返回空数组,避免无效输入。
- 开发者需确保输入值符合预期类型,以正确利用此函数进行数据转换。
原文内容
Converts an object-like value to an array.
Parameters
$maybe_objectmixedrequired-
The value being evaluated.
Source
function rest_sanitize_object( $maybe_object ) {
if ( '' === $maybe_object ) {
return array();
}
if ( $maybe_object instanceof stdClass ) {
return (array) $maybe_object;
}
if ( $maybe_object instanceof JsonSerializable ) {
$maybe_object = $maybe_object->jsonSerialize();
}
if ( ! is_array( $maybe_object ) ) {
return array();
}
return $maybe_object;
}
Changelog
| Version | Description |
|---|---|
| 5.5.0 | Introduced. |