Repository navigation
API Reference
Every public member of InitPHP\Translator\Translator and
InitPHP\Translator\TranslatorInterface.
All configuration methods return the same instance, so calls chain
($lang->setDir(...)->setDefault(...)->change(...)).
final class Translator implements TranslatorInterfaceTranslator is final. Depend on TranslatorInterface
and compose rather than subclass.
Internal state in brief:
| State | Meaning |
|---|---|
| base directory | set by setDir(); language packs live here |
| layout mode | file (default) or directory — useFile() / useDirectory()
|
| default language | the fallback language — setDefault()
|
| active language | the language read first — setDefault() / change()
|
| container | in-memory cache of loaded languages |
public function setDir(string $dir): self;Sets the base directory that holds the language packs. A trailing / or \ is
trimmed. Call this before loading a language.
-
$dir— path to the directory containing the language files/directories. -
Throws
TranslatorExceptionif$diris not an existing directory.
$lang->setDir(__DIR__ . '/languages/');public function useFile(): self;Selects the one-file-per-language layout, where each language is a single
<language>.php file. This is the default, so the call is optional. Must run
before any language is loaded.
-
Throws
TranslatorExceptionif the mode is changed after a language has already loaded.
See File Mode.
public function useDirectory(): self;Selects the one-directory-per-language layout, where each *.php file becomes a
namespace keyed by its lower-cased file name. Must run before any
language is loaded.
-
Throws
TranslatorExceptionif the mode is changed after a language has already loaded.
$lang->useDirectory()->setDir(__DIR__ . '/languages/')->setDefault('en');See Directory Mode.
public function setDefault(string $default): self;Sets and eagerly loads the default (fallback) language. If no active language has been chosen yet, this language also becomes the active one.
-
$default— language identifier (a file name without extension in file mode, or a sub-directory name in directory mode). It is joined into a path and the file isrequired, so it must be a single path component (see Validate user-supplied language codes); validate request input against an allow-list anyway — see Validate user-supplied language codes. -
Throws
TranslatorExceptionif the identifier is empty, contains/,\or a NUL byte, or consists only of dots and spaces, if the directory is unset, or the language pack is missing, unreadable, or does not return an array. On any of these the translator keeps its previous state (see Exceptions).
$lang->setDefault('en');public function change(string $current): self;Switches the active language, loading it on first use. If no default language has been set yet, the given language also becomes the default.
-
$current— language identifier to activate. LikesetDefault(), it is joined into a path and the file isrequired, so the same rule applies. Do not pass request input directly; check it against an allow-list first — see Validate user-supplied language codes. -
Throws
TranslatorExceptionunder the same conditions assetDefault().
$lang->change('tr');public function translate(string $key, ?string $fallback = null, array $context = []): string;Returns the resolved, interpolated translation for $key.
-
$key— the translation key; use dots for nested values (admin.dashboard,errors.http.404). -
$fallback— text returned when the key is missing from the active language.''and'0'count as provided; onlynullmeans "no fallback". -
$context—array<string, mixed>of placeholder values. Scalars and__toString()-able objects are interpolated; arrays and other objects are ignored. See Placeholders. -
Returns the translation, the interpolated fallback, or
$keyitself.
Resolution order: active language → inline fallback → default language → the key. See Keys & Fallback.
$lang->translate('welcome', 'Hi {user}', ['user' => 'Ada']);public function render(string $key, ?string $fallback = null, array $context = []): void;Echoes the value that translate() would return. Same parameters.
$lang->render('welcome', null, ['user' => 'Ada']); // prints "Welcome Ada"public function _r(string $key, ?string $fallback = null, array $context = []): string;Deprecated since 1.0. Backward-compatible alias of
translate(). Prefertranslate()in new code. Still fully functional.
public function _e(string $key, ?string $fallback = null, array $context = []): void;Deprecated since 1.0. Backward-compatible alias of
render(). Preferrender()in new code. Still fully functional.
public function __debugInfo(): array;Returns a debug snapshot used by var_dump():
[
'system' => 'file', // or 'directory'
'default' => 'en', // or null
'current' => 'tr', // or null
'container' => [...], // the active language's loaded data (present only when a language is active)
]interface TranslatorInterfaceThe contract implemented by Translator. Type-hint this in your
services so you can swap or decorate the implementation.
It declares every method above except __debugInfo(). The configuration methods
are declared to return TranslatorInterface; the concrete Translator narrows
that to self.
use InitPHP\Translator\TranslatorInterface;
final class GreetingService
{
public function __construct(private TranslatorInterface $lang)
{
}
public function greet(string $user): string
{
return $this->lang->translate('welcome', 'Welcome {user}', ['user' => $user]);
}
}| Method | Returns | Loads from disk? |
|---|---|---|
setDir |
self |
no |
useFile / useDirectory
|
self |
no |
setDefault |
self |
yes (the default language) |
change |
self |
yes (on first use of a language) |
translate |
string |
no (uses the in-memory cache) |
render |
void (echoes) |
no |
_r / _e
|
as above | no |
__debugInfo |
array |
no |
-
Keys & Fallback — the resolution semantics of
translate(). -
Placeholders — how
$contextis applied. - Exceptions — every condition that throws.
initphp/translator · MIT License · part of the InitPHP family
Source · Issues · Discussions · Packagist · Contributing · Security Policy
Getting Started
Core Usage
Reference
Practical Guides
Migration & Help