问题描述

当通过 WordPress 片段/教程/插件查看时,我经常看到 add_action()add_filter()被放置在函数声明之前:

add_action( 'publish_post', 'email_friends' );

function email_friends( $post_ID ) {
   $friends = 'bob@example.org, susie@example.org';
   mail( $friends, "sally's blog updated" , 'I just put something on my blog: http://blog.example.com' );
   return $post_ID;
}

从逻辑的角度来看,这对我来说没有意义。为什么在代码中调用函数后放置函数?这通常是如何处理同样的情况:

function email_friends( $post_ID )  {
   $friends = 'bob@example.org, susie@example.org';
   mail( $friends, "sally's blog updated" , 'I just put something on my blog: http://blog.example.com' );
   return $post_ID;
}

add_action( 'publish_post', 'email_friends' );

我知道这两种情况都有效,但是有一个或另一个具体的优势吗?大约 90%的时间我看到第一种情况被使用,所以这让我相信在某种程度上有益处。

最佳解决方案

它更容易阅读:什么时候叫什么?如果你正在调试一个钩子,你可以立即看到你是否必须阅读该功能:如果不是你的钩子,你可以跳过代码。

在我的主题和插件中,我结合了顶部的操作,过滤器和缩写代码的所有注册,并将钩子添加到 PHPDoc 块中:

add_action( 'wp_head',  'foo' );
add_action( 'shutdown', 'bar' );

/**
 * Foo you!
 *
 * @wp-hook wp_head
 * @return  void
 */
function foo()
{
    print '<!-- foo -->';
}

次佳解决方案

实际上没有什么真正的区别,我比较喜欢跟随第一种情况,因为在一个地方打电话,并定义下面的功能。 PHP 在运行任何东西之前解析整个文档,如果函数被正确定义,一切都将正常工作,在任何一种情况下都没有任何优势。

我相信这里说的正确的一点是:你的船漂浮什么东西:)

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。