php PHP在<<<EOF字符串中使用Gettext

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3694327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:44:26  来源:igfitidea点击:

PHP using Gettext inside <<<EOF string

phpgettexteof

提问by FFish

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 的 EOF 字符串来格式化 HTML 内容,而无需转义引号等。如何使用该字符串中的函数?

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

回答by Pekka

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:

据我在手册中看到,不可能在 HEREDOC 字符串中调用函数。一个麻烦的方法是事先准备好单词:

<?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.

想到的一个变通办法是用魔法 getter 方法构建一个类。

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:

然后,您可以使用以下语法在 HEREDOC 块内执行 gettext 查找:

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

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

$translate->World由于魔法 getter 方法,将自动转换为 gettext 查找。

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:

要将此方法用于带有空格或特殊字符的单词(例如名为 的 gettext 条目Hello World!!!!!!,您必须使用以下符号:

 $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.

更新:正如@mario 发现的那样,毕竟可以从 HEREDOC 字符串调用函数。我认为使用这样的 getter 是一个时尚的解决方案,但使用直接函数调用可能更容易。请参阅有关如何执行此操作的评论。

回答by Your Common Sense

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

据我所知,您只是错误地添加了 heredoc
无需在这里使用丑陋的 heredoc 语法。
只需删除它,一切都会起作用:

<p>Hello</p>
<p><?= _("World"); ?></p>