PHP using Gettext inside <<<EOF string

后端 未结 2 714
野性不改
野性不改 2020-12-08 01:47

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?



        
2条回答
  •  悲哀的现实
    2020-12-08 02:37

    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:

    Hello

    $world

    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 = <<Hello

    {$translate->World}

    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.

提交回复
热议问题