In file mode each language is a single PHP file named <language>.php inside
the base directory. This is the default layout.
languages/
en.php
tr.php
fr.php
File mode is active by default, so useFile() is optional. Call it explicitly
when you want the intent to be obvious, but always before the first language
is loaded:
use InitPHP\Translator\Translator;
$lang = new Translator();
$lang->useFile()
->setDir(__DIR__ . '/languages/')
->setDefault('en');Each file returns an associative array. 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',
],
];echo $lang->translate('hello'); // "Hello"
echo $lang->translate('errors.e404'); // "Not Found" (nested key)
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 only once; subsequent lookups use the in-memory cache.
- A missing
<language>.phpthrows aTranslatorException. - A file that does not
returnan array throws aTranslatorException.
See Directory mode for grouping translations across multiple files per language.