我可以在创建变量和使用变量之间使用PHP输出缓冲吗


Can I use PHP output buffering in between creating a variable and using it?

我不太了解PHP输出缓冲的工作原理,也不知道这是否可能:我想按以下顺序执行:

  1. 声明PHP变量$foo
  2. 开始和结束输出缓冲区以声明变量$bar
  3. 使用变量$foo

当我第二次尝试使用$foo时,我似乎无意中清除了它。

代码示例:

<?php
$foo = 'some value';
ob_start();
include('some_file.php');
//I want to use output buffering since some_file.php has a number of echo statements that I want to concatenate into one variable.  Maybe there's a better way?
$bar = ob_get_clean();
ob_end_flush();
echo $bar;
echo $foo;
?>

在上面的例子中,$bar工作得很好,但$foo在末尾是未定义的。我认为我对底层概念的理解还不够好,无法确切地知道这里的代码中发生了什么。我希望能够使用缓冲区(或其他方法?(使some_file.php中的所有echo语句都指向一个字符串,同时保留以前php代码中的变量。有办法做到这一点吗?

在上面的例子中,$bar工作得很好,但$foo在的末尾是未定义的

你可能是unsetsome_file.php里面。你的剧本在其他方面都很好。您也可以通过some_file.php:中的returnreturn其他文件的输出

// some_file.php
...
return $output;
// main file
...
$bar = include('some_file.php');