Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP using Gettext inside <<<EOF string

Tags:

php

eof

gettext

I use PHP's EOF string to format HTML content without the hassle of having to escape quotes etc. How can I use the function inside this string?

<?php     $str = <<<EOF     <p>Hello</p>     <p><?= _("World"); ?></p> EOF;     echo $str; ?> 
like image 278
FFish Avatar asked Sep 12 '10 09:09

FFish


1 Answers

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php      $world = _("World");      $str = <<<EOF     <p>Hello</p>     <p>$world</p> EOF;     echo $str; ?> 

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator {  public function __get($name) {   return _($name); // Does the gettext lookup   }  } 

Initialize an object of the class at some point:

  $translate = new Translator(); 

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF     <p>Hello</p>     <p>{$translate->World}</p> EOF;     echo $str; ?> 

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"} 

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

like image 56
Pekka Avatar answered Sep 23 '22 03:09

Pekka