我使用PHP的EOF字符串来格式化HTML内容,而不必担心必须转义引号等.如何在此字符串中使用该函数?
<?php
$str = <<<EOF
<p>Hello</p>
<p><?= _("World"); ?></p>
EOF;
echo $str;
?>
Run Code Online (Sandbox Code Playgroud)
Pek*_*ica 88
据我在手册中看到,无法在HEREDOC字符串中调用函数.一种繁琐的方法是事先准备好这些词:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
Run Code Online (Sandbox Code Playgroud)
想到一个解决方法的想法是使用魔术getter方法构建一个类.
你会声明一个这样的类:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Run Code Online (Sandbox Code Playgroud)
在某个时刻初始化类的对象:
$translate = new Translator();
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下语法在HEREDOC块内执行gettext查找:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
Run Code Online (Sandbox Code Playgroud)
$translate->World
由于魔术getter方法,将自动转换为gettext查找.
要将此方法用于包含空格或特殊字符的单词(例如,名为gettext的条目Hello World!!!!!!
,您必须使用以下表示法:
$translate->{"Hello World!!!!!!"}
Run Code Online (Sandbox Code Playgroud)
这都是未经测试但应该有效.
更新:正如@mario发现的那样,毕竟可以从HEREDOC字符串中调用函数.我认为使用这样的getter是一个时髦的解决方案,但使用直接函数调用可能更容易.请参阅有关如何执行此操作的注释.