-
-
Notifications
You must be signed in to change notification settings - Fork 2
File Mode
In file mode, each language is a single PHP file named <language>.php
inside the base directory. This is the default layout, so useFile() is
optional.
languages/
en.php
tr.php
fr.php
File mode is active by default. Call useFile() explicitly when you want the
intent to be obvious — but always before the first language loads:
use InitPHP\Translator\Translator;
$lang = new Translator();
$lang->useFile() // optional; this is the default
->setDir(__DIR__ . '/languages/')
->setDefault('en');Each file returns an associative array. Leaf values are strings; nested
arrays create dot-delimited keys:
<?php
// languages/en.php
return [
'hello' => 'Hello',
'welcome' => 'Welcome {user}',
'errors' => [
'e404' => 'Not Found',
'e500' => 'Server Error',
'http' => [
'unauthorized' => 'Unauthorized',
],
],
];A file that does not return an array throws a
TranslatorException:
<?php
// languages/broken.php — WRONG
$messages = ['hello' => 'Hi']; // never returned → throws on loadecho $lang->translate('hello'); // "Hello"
echo $lang->translate('errors.e404'); // "Not Found" (nested)
echo $lang->translate('errors.http.unauthorized'); // "Unauthorized" (deeply nested)
echo $lang->translate('welcome', null, [ // with a placeholder
'user' => 'Ada',
]); // "Welcome Ada"$lang->change('tr');
echo $lang->translate('hello'); // value from tr.phpA language file is read from disk once; later lookups use the in-memory cache. Switching back to a language you already loaded does not re-read it.
If a key resolves to an array (a "namespace") rather than a string leaf, it is treated as a miss and falls through the resolution chain — it never throws:
// 'errors' is an array, not a translation string
echo $lang->translate('errors'); // "errors"
echo $lang->translate('errors.http'); // "errors.http"- A missing
<language>.phpthrows aTranslatorException. - A file that does not
returnan array throws aTranslatorException.
Note that a missing key never throws — only a missing or invalid file does. See Exceptions for the full list.
Use file mode when each language fits comfortably in one file. Reach for
Directory Mode when you want to split a language across
several files (e.g. admin.php, user.php, emails.php) addressed as
admin.*, user.*, emails.*.
- Keys & Fallback — how lookups resolve and fall back.
-
Placeholders —
{name}interpolation in detail. - Directory Mode — the multi-file layout.
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