_wp_filter_build_unique_id()
云策文档标注
概述
_wp_filter_build_unique_id() 函数用于为钩子回调函数生成唯一的字符串 ID,主要用于内部处理回调标识。该函数根据回调类型返回相应的唯一标识,支持字符串、对象和数组形式的回调。
关键要点
- 函数返回回调的唯一 ID,用于数组键,若回调无效则返回 null。
- 字符串回调直接返回原字符串,静态方法回调返回类名::方法名格式。
- 对象回调(如闭包)使用 spl_object_hash() 生成哈希值并拼接方法名。
- 参数 $hook_name 和 $priority 在函数中未使用,仅用于兼容性。
- 自 WordPress 5.3.0 起,移除了 spl_object_hash() 的变通方法,并确保始终返回字符串。
代码示例
function _wp_filter_build_unique_id( $hook_name, $callback, $priority ) {
if ( is_string( $callback ) ) {
return $callback;
}
if ( is_object( $callback ) ) {
// Closures are currently implemented as objects.
$callback = array( $callback, '' );
} else {
$callback = (array) $callback;
}
if ( is_object( $callback[0] ) ) {
// Object class calling.
return spl_object_hash( $callback[0] ) . $callback[1];
} elseif ( is_string( $callback[0] ) ) {
// Static calling.
return $callback[0] . '::' . $callback[1];
}
return null;
}注意事项
- 此函数是内部函数,通常不应直接调用,而是通过 WP_Hook 类的方法间接使用。
- 在 WordPress 5.3.0 之前,$hook_name 和 $priority 参数有特定用途,但之后已不再使用。
- 确保传递有效的回调参数,否则函数可能返回 null,影响钩子管理功能。
原文内容
Builds a unique string ID for a hook callback function.
Description
Functions and static method callbacks are just returned as strings and shouldn’t have any speed penalty.
Parameters
$hook_namestringrequired-
Unused. The name of the filter to build ID for.
$callbackcallable|string|arrayrequired-
The callback to generate ID for. The callback may or may not exist.
$priorityintrequired-
Unused. The order in which the functions associated with a particular action are executed.
Source
function _wp_filter_build_unique_id( $hook_name, $callback, $priority ) {
if ( is_string( $callback ) ) {
return $callback;
}
if ( is_object( $callback ) ) {
// Closures are currently implemented as objects.
$callback = array( $callback, '' );
} else {
$callback = (array) $callback;
}
if ( is_object( $callback[0] ) ) {
// Object class calling.
return spl_object_hash( $callback[0] ) . $callback[1];
} elseif ( is_string( $callback[0] ) ) {
// Static calling.
return $callback[0] . '::' . $callback[1];
}
return null;
}