_validate_cache_id()
云策文档标注
概述
_validate_cache_id() 函数用于验证给定的缓存 ID 是否为整数或整数形式的字符串,确保其符合 WordPress 缓存系统的要求。
关键要点
- 函数检查 $object_id 是否为整数或可转换为整数的字符串(如 "16"),其他类型如浮点数或非整数字符串视为无效。
- 验证逻辑使用 is_int() 和字符串转换比较,避免依赖可选的 PHP filter 扩展。
- 无效输入会触发 _doing_it_wrong() 警告,并返回 false,以帮助开发者调试。
代码示例
function _validate_cache_id( $object_id ) {
if ( is_int( $object_id )
|| ( is_string( $object_id ) && (string) (int) $object_id === $object_id ) ) {
return true;
}
$message = sprintf( __( 'Object ID must be an integer, %s given.' ), gettype( $object_id ) );
_doing_it_wrong( '_get_non_cached_ids', $message, '6.3.0' );
return false;
}注意事项
- 此函数从 WordPress 6.3.0 版本引入,用于内部缓存验证,开发者应确保传递给缓存相关函数的 ID 符合此规范。
- 相关函数包括 __() 用于翻译和 _doing_it_wrong() 用于错误处理,需在开发中正确使用。
原文内容
Checks whether the given cache ID is either an integer or an integer-like string.
Description
Both 16 and "16" are considered valid, other numeric types and numeric strings (16.3 and "16.3") are considered invalid.
Parameters
$object_idmixedrequired-
The cache ID to validate.
Source
function _validate_cache_id( $object_id ) {
/*
* filter_var() could be used here, but the `filter` PHP extension
* is considered optional and may not be available.
*/
if ( is_int( $object_id )
|| ( is_string( $object_id ) && (string) (int) $object_id === $object_id ) ) {
return true;
}
/* translators: %s: The type of the given object ID. */
$message = sprintf( __( 'Object ID must be an integer, %s given.' ), gettype( $object_id ) );
_doing_it_wrong( '_get_non_cached_ids', $message, '6.3.0' );
return false;
}
Changelog
| Version | Description |
|---|---|
| 6.3.0 | Introduced. |