Drupal - What's the difference between using $this->t('text') and t('text') in a block plugin

To be exact on your question: there's no difference in internal implementation.

But as a best practice, you should be using $this->t instead of the global t wherever possible. If you check the function, t is returning a new TranslateableMarkup object.

If your class says $this->t is not defined, you can add the StringTranslationTrait to add the behavior or inject it as a dependency.

Using this trait will add t() and formatPlural() methods to the class. These must be used for every translatable string, similar to how procedural code must use the global functions t() and \Drupal::translation()->formatPlural(). This allows string extractor tools to find translatable strings.

If the class is capable of injecting services from the container, it should inject the 'string_translation' service and assign it to $this->stringTranslation.

So as a best practice rule, you generally do not want to mix procedural within OOP unless completely unavoidable (e.g. native PHP functions).


The documentation for t() states:

When possible, use the \Drupal\Core\StringTranslation\StringTranslationTrait::t(). Otherwise create a new \Drupal\Core\StringTranslation\TranslatableMarkup object directly.

It doesn't explain the reason for this, but if you look at the comment on the documentation page, it will give you a reason for using that trait method, or that class.

Classes can be tested individually with PHPUnit, which runs without bootstrapping core, but the t() function is only available when core is bootstrapped.
Using $this->t() and StringTranslationTrait allows the translation to be mocked, so the class can be tested in isolation with PHPUnit.

Tags:

Plugins

8

Blocks