Translates a message through the active gettext catalog. It is an alias of gettext().
What Is _() in PHP?
Translates a message through the active gettext catalog. It is an alias of gettext().
Its syntax is:
_(string $message): string
Parameters:
$message— Accepted as string; required argument.
Return type: string. The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.
Availability: Requires the gettext extension and a configured message catalog.
Example 1: Basic Usage
<?php
echo _("Save changes");
Output:
Save changes
The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.
Example 2: A Different Input
<?php
echo _("Cancel");
Output:
Cancel
The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.
Practical Example: Applying It in a Program
<?php
$labels = ["Save changes", "Cancel", "Help"];
foreach ($labels as $label) { echo _($label) . PHP_EOL; }
Output:
Save changes
Cancel
Help
The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.
Important Behavior and Edge Cases
- Key behavior: The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.
- Environment: Requires the gettext extension and a configured message catalog.
Comparison With Related Functions
| Function | Purpose |
|---|---|
_() | translates a message through the active gettext catalog. It is an alias of gettext(). |
gettext() | gettext() is the full name; _() is its shorthand alias. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: The result depends on installed gettext catalogs and the active locale | The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned. |
Key Takeaways
- translates a message through the active gettext catalog. It is an alias of gettext().
- The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.
- Requires the gettext extension and a configured message catalog.
Summary: The result depends on installed gettext catalogs and the active locale. Without a translation, the original message is generally returned.