"double underscore" 和 "underscore x" 有什么区别?

What's the difference between "double underscore" and "underscore x"?

在 PHP 中,特别是在 Wordpress 中,__('string')_x('string') 之间有什么区别?

我正在阅读 Wordpress 文档并感到困惑。以下混淆的好例子取自 Wordpress doc for register_post_type() 的示例代码:

$labels = array(
    'name'               => _x( 'Books', 'post type general name', 'your-plugin-textdomain' ),
    'singular_name'      => _x( 'Book', 'post type singular name', 'your-plugin-textdomain' ),
    'menu_name'          => _x( 'Books', 'admin menu', 'your-plugin-textdomain' ),
    'name_admin_bar'     => _x( 'Book', 'add new on admin bar', 'your-plugin-textdomain' ),
    'add_new'            => _x( 'Add New', 'book', 'your-plugin-textdomain' ),
    'add_new_item'       => __( 'Add New Book', 'your-plugin-textdomain' ),
    'new_item'           => __( 'New Book', 'your-plugin-textdomain' ),
    'edit_item'          => __( 'Edit Book', 'your-plugin-textdomain' ),
    'view_item'          => __( 'View Book', 'your-plugin-textdomain' ),
    'all_items'          => __( 'All Books', 'your-plugin-textdomain' ),
    'search_items'       => __( 'Search Books', 'your-plugin-textdomain' ),
    'parent_item_colon'  => __( 'Parent Books:', 'your-plugin-textdomain' ),
    'not_found'          => __( 'No books found.', 'your-plugin-textdomain' ),
    'not_found_in_trash' => __( 'No books found in Trash.', 'your-plugin-textdomain' )
);

在WordPress中,_x()__()都是翻译函数。 _x() 允许您为翻译指定上下文:

<?php _x( $text, $context, $domain ); ?>

__() 没有:

<?php __( $text, $domain ); ?>

上下文选项适用于直译可能无法产生预期结果的各种情况。

Since the string 'Read' on its own could have one of several different meanings in English, context is given so that translators know that they should be supplying a short term that means "Books I have read."

一些其他示例可能是:"date"、"type"、"right"、"leaves" 等

来源:WordPress Codex

__(..) 直接从字符串 A 翻译成字符串 B

_x(..) 让您提供上下文。例如,假设您有 2 个英语字符串表示相同的意思,但在另一种语言中可能意思不同,那么您可以使用 _x 提供上下文,这样尽管您的字符串在英语中是相同的,您可以将它们翻译成另一种语言的 2 个不同的字符串。

因此,作为您问题中的示例,您有

__( 'All Books', 'your-plugin-textdomain' ),

使用 __ 是因为作者一定认为“'All books' 在使用该术语的每个上下文中始终表示 'All books'”。但是,让我们考虑 _x:

的用例

_x( 'Books', 'post type general name', 'your-plugin-textdomain' )

所以作者在这里想“'Books' 是一个非常笼统的术语,根据我们在应用程序中使用术语 'Books' 的上下文,我们可能希望以不同的方式翻译这个术语" - 因此附加参数用作上下文。当将上述行的 'Books' 翻译成另一种语言时,我们会知道我们在插件文本域的上下文中谈论书籍。

来源:http://wpengineer.com/2237/whats-the-difference-between-__-_e-_x-and-_ex/