Skip to content

API Reference

github-actions[bot] edited this page Nov 25, 2026 · 4 revisions

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(...)).

Translator

final class Translator implements TranslatorInterface

Translator 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

setDir()

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 TranslatorException if $dir is not an existing directory.
$lang->setDir(__DIR__ . '/languages/');

useFile()

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.

See File Mode.


useDirectory()

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.

$lang->useDirectory()->setDir(__DIR__ . '/languages/')->setDefault('en');

See Directory Mode.


setDefault()

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 is required, 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 TranslatorException if 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');

change()

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.

$lang->change('tr');

translate()

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; only null means "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 $key itself.

Resolution order: active language → inline fallback → default language → the key. See Keys & Fallback.

$lang->translate('welcome', 'Hi {user}', ['user' => 'Ada']);

render()

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"

_r()

public function _r(string $key, ?string $fallback = null, array $context = []): string;

Deprecated since 1.0. Backward-compatible alias of translate(). Prefer translate() in new code. Still fully functional.


_e()

public function _e(string $key, ?string $fallback = null, array $context = []): void;

Deprecated since 1.0. Backward-compatible alias of render(). Prefer render() in new code. Still fully functional.


__debugInfo()

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)
]

TranslatorInterface

interface TranslatorInterface

The 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 summary

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

Where to go next

Clone this wiki locally