PHP自定义钩子执行execute_event时var_dump返回null是什么原因
问题原因
- 你的
Hooks::execute()方法和全局封装的execute_event()函数都没有显式定义return语句,PHP中无return的函数执行后默认返回null,这是var_dump输出null的直接原因。 - 你当前实现的是仅执行回调的动作钩子逻辑,没有收集回调返回值的处理,即使绑定的
login_page_body_classes函数返回了类名字符串,也不会被钩子执行逻辑传递出来。 - 额外bug:全局
is_event()函数漏写return,就算目标钩子存在也不会返回true。
修复方案
1. 修改钩子核心代码
<?php /** * Hooks Class * * @since 1.0.0 */ class Hooks { private $hooks; function __construct() { $this->hooks = []; } function add_event( $where, $callback, $priority = 50 ) { if ( !isset( $this->hooks[$where] ) ) { $this->hooks[$where] = []; } $this->hooks[$where][$callback] = $priority; } function remove_event( $where, $callback ) { if ( isset( $this->hooks[$where][$callback] ) ) { unset( $this->hooks[$where][$callback] ); } } function is_event( $where ) { if ( isset( $this->hooks[$where] ) ) { return true; } return false; } // 重写execute方法,支持收集返回值的过滤钩子逻辑 function execute( $where, $args = [] ) { if ( !isset( $this->hooks[$where] ) || !is_array( $this->hooks[$where] ) ) { // 无绑定钩子时返回第一个参数作为默认值 return $args[0] ?? null; } arsort( $this->hooks[$where] ); // 取出第一个参数作为要修改的初始值 $filtered_value = $args[0] ?? null; foreach ( $this->hooks[$where] as $callback => $priority ) { // 将当前修改后的值作为第一个参数传给回调,支持链式修改 $filtered_value = call_user_func_array( $callback, [$filtered_value, ...array_slice($args, 1)] ); } return $filtered_value; } } $hooks_class = new Hooks; function add_event( $where, $callback, $priority = 50 ) { global $hooks_class; if ( isset( $hooks_class ) ) { $hooks_class->add_event( $where, $callback, $priority ); } } function remove_event( $where, $callback ) { global $hooks_class; if ( isset( $hooks_class ) ) { $hooks_class->remove_event( $where, $callback ); } } // 补全return语句 function is_event( $where ) { global $hooks_class; if ( isset( $hooks_class ) ) { return $hooks_class->is_event( $where ); } return false; } // 补全return语句,把execute的结果返回 function execute_event( $where, $args = [] ) { global $hooks_class; if ( isset( $hooks_class ) ) { return $hooks_class->execute( $where, $args ); } return null; }
2. 修改调用逻辑
执行钩子时传入初始的空字符串作为类名的默认值:
var_dump( execute_event( '_body_class', [''] ) );
如果在is_login_page()返回true的场景下,就能拿到你定义的类名字符串。
内容的提问来源于stack exchange,提问作者Noman Nawaz
相关产品推荐
相关产品推荐

