函式名:MessageFormatter::formatMessage()
適用版本:PHP 5 >= 5.3.0, PHP 7
用法: MessageFormatter::formatMessage() 函式用於根據給定的訊息模板和引數格式化訊息。它使用 ICU 訊息格式來支援多語言和複雜的訊息格式化。
語法:
public static string MessageFormatter::formatMessage(string $locale, string $pattern, array $args): string
引數:
$locale
:要使用的區域設定(例如:"en_US")。$pattern
:訊息模板,它可以包含佔位符來插入引數。$args
:包含要插入到訊息中的引數的陣列。
返回值: 返回格式化後的訊息字串。
示例:
$locale = 'en_US';
$pattern = 'Hello, {0}! You have {1, number} messages.';
$args = ['John', 42];
$message = MessageFormatter::formatMessage($locale, $pattern, $args);
echo $message;
輸出:
Hello, John! You have 42 messages.
解釋:
在上面的示例中,我們使用英文美國區域設定(en_US)和訊息模板("Hello, {0}! You have {1, number} messages.")來格式化訊息。訊息模板中的 {0}
和 {1, number}
是佔位符,分別表示第一個和第二個引數。在 $args
陣列中,我們提供了兩個引數值,分別是 'John'
和 42
。最終,呼叫 MessageFormatter::formatMessage()
函式會將引數插入到模板中,並返回格式化後的訊息字串。在這個例子中,輸出的訊息是 "Hello, John! You have 42 messages."。