PHP在<<< EOF字符串中使用Gettext [英] PHP using Gettext inside <<<EOF string

查看:79
本文介绍了PHP在<<< EOF字符串中使用Gettext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP的EOF字符串设置HTML内容的格式,而不必担心使用引号引起的麻烦.如何在此字符串中使用该函数?

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

推荐答案

据我在

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.

您将这样声明一个类:

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

在某个时刻初始化该类的对象:

Initialize an object of the class at some point:

  $translate = new Translator();

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

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将通过魔术的getter方法自动转换为gettext查找.

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

要将这种方法用于带有空格或特殊字符的单词(例如,名为Hello World!!!!!!的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:

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

这都是未经测试的,但应该可以使用.

This is all untested but should work.

更新:@mario发现,毕竟可以从HEREDOC字符串中调用函数.我认为使用这样的吸气剂是一种时尚的解决方案,但是使用直接函数调用可能会更容易.查看有关如何执行此操作的评论.

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.

这篇关于PHP在&lt;&lt;&lt; EOF字符串中使用Gettext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆