【问题标题】:How can I store PHP code inside a 'heredoc' variable?如何将 PHP 代码存储在“heredoc”变量中?
【发布时间】:2017-09-01 17:47:01
【问题描述】:

我想将以下代码存储在 HEREDOC 变量中:

<?php
    $var = 'test';
    echo $var;
?>

像这样:

$hered = <<<HERED
<?php
    $var = 'test';
    echo $var;
?>
HERED;

问题在于 HEREDOC 的工作方式类似于双引号 "" - 这意味着每个美元符号 ($) 都必须替换为 \$...

有没有办法在不执行这种操作的情况下使用HEREDOC?

【问题讨论】:

  • 问题应该是:你为什么要这样做?你在这里做的事情对我来说就像代码味道。
  • 如果你以后对eval这样做:请不要!

标签: php


【解决方案1】:

是的,有。查看nowdoc 语法:

$hello = 'hey';
$echo <<<'EOS'
$hello world!
EOS;
//Output: $hello world

【讨论】:

  • PHP 5.2 已于 2.5 年前终止。从那时起,旧的 PHP 版本不再有安全更新,因此任何仍在运行 5.3 之前的 PHP 的人都应该尽快计划升级。
  • 但是如何用heredoc做到这一点?
  • @simPod 你为什么要这么做?来自文档:Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.php.net/manual/en/…
  • @Xatenev 因为您可能需要完成部分解析,所以您需要 heredoc。
  • @simPod 听起来你需要一个模板引擎。
【解决方案2】:

可以使用\:

echo <<<HEREDOC
<?php
    \$var = 'test';
    echo \$var;
?>
HEREDOC;

我知道现在有 doc,但例如我当前的用例需要 heredoc,因为有些美元需要转义,有些则不需要:

$variableNotToEscape = 'this should be output';
echo <<<HEREDOC
$variableNotToEscape
\$variableNotToEscape
HEREDOC;

返回

this should be output
$variableNotToEscape

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2015-01-28
    • 1970-01-01
    • 2023-03-08
    • 2021-06-22
    • 2012-11-05
    相关资源
    最近更新 更多