Is there a way to get translated string in php code?

Something like this:

$string = __('something');
foreach ($stores as $store){
 echo $store->getName().': '.$store->getTranslated($string)."\n";

\\-- output:  
english: someting
italian: qualcosa
french: quelque chose

EDIT: @Vinz suggestion could be a nice workaround but I need to use __() function or prashes won't be collected for dictionary.

in magento 1 I used;

$newLocaleCode = Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeCode);
$initialEnvironmentInfo = Mage::getSingleton('core/app_emulation')->startEnvironmentEmulation($storeCode);
Mage::getSingleton('core/translate')->setLocale($newLocaleCode)->init(Mage_Core_Model_App_Area::AREA_FRONTEND, true);

so after some research i found this:

  * \Magento\Store\Model\App\Emulation
 protected $emulation;

public function __construct(\Magento\Store\Model\App\Emulation $emulation) {
   $this->emulation = $emulation;

 * example function in which we want to emulate a stores environment  
public function example($storeId, $area = 'frontend') {

   //starting the store emulation with area defined for admin
   $this->emulation->startEnvironmentEmulation($storeId, 'adminhtml');

   //you can update or save a product attributes here with correct scope or anything else you want to do, perform some test

   // discard the emulated environment after doing your work


at this link: https://webkul.com/blog/magento2-store-emulation/

This works fine.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.