You need to enable JavaScript to run this app. 如何在PHP heredoc字符串中使用print_r函数?
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP heredoc字符串中使用print_r函数?

解决HEREDOC中使用print_r输出调试信息的问题

你的问题核心在于print_r默认直接输出内容,而非返回字符串,而且HEREDOC里的函数调用写法需要注意格式。直接用{$print_r($_GET)}时,print_r会先把内容输出到页面,不会将结果嵌入到$html变量中,所以你看不到它出现在调试区域里。

简便的修复方法

给print_r加上第二个参数true,让它返回字符串而非直接输出,同时在HEREDOC里正确使用函数调用的语法:

function bottom_module() {
    // 开启session才能访问$_SESSION
    session_start();

    $html = <<<"OUTPUT"
      <footer>
        ...
      </footer>

      <aside id="debug">
        <hr>
        <h3>Debug Area</h3>
        <pre>
          GET Contains:
          {$print_r($_GET, true)}
          POST Contains:
          {$print_r($_POST, true)}
          SESSION Contains:
          {$print_r($_SESSION, true)}
        </pre>
      </aside>

    </body>
  </html>
OUTPUT;
    echo $html;
}

更清晰的写法(可选)

如果觉得HEREDOC里嵌套函数调用不够直观,可以提前把调试内容赋值给变量,再在HEREDOC里引用:

function bottom_module() {
    session_start();
    
    $debug_get = print_r($_GET, true);
    $debug_post = print_r($_POST, true);
    $debug_session = print_r($_SESSION, true);

    $html = <<<"OUTPUT"
      <footer>
        ...
      </footer>

      <aside id="debug">
        <hr>
        <h3>Debug Area</h3>
        <pre>
          GET Contains:
          $debug_get
          POST Contains:
          $debug_post
          SESSION Contains:
          $debug_session
        </pre>
      </aside>

    </body>
  </html>
OUTPUT;
    echo $html;
}

不需要手动单独加调试模块,只要调整print_r的使用方式就能在HEREDOC里正常输出调试信息。

内容的提问来源于stack exchange,提问作者iSteeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:18:19