PHP在一个页面中包含多个文件


PHP include file multiple times in one page

我有一个名为kal_test.php的php文件,它为变量$vbl提供了一个值。该变量在名为kal_generator.php的文件中是必需的,该文件从该变量生成一个表(我将省去详细信息)。它是这样的:


[kal_test.php]

<?php
$vbl = "14/09/2011";
include ("kal_generator.php");
?>
[kal_test.php]

<?php
// Long code converts the $vbl into a 2-dimensional array called $output
// I'll spare you the details (it works fine by the way)
?>
<table>
  <tr><th>bla</th><th>blabla</th></tr>
<?php
foreach ($output as $v1) {
    echo "<tr>";
    foreach ($v1 as $v2) {
        echo "<td>$v2</td>";
    }
    echo "</tr>'n";
}
?>
</table>

这个设置工作得很好,但我不能让两个出现在同一个页面上,像这样:

[kal_test.php]

<?php
$vbl = "14/09/2011";
include ("kal_generator.php");
$vbl = "21/09/2011";
include ("kal_generator.php");
?>

这将给出以下结果:

//here comes the header
<table> // table created with $vbl = "14/09/2011"
  <tr><th>bla</th><th>blabla</th></tr>
  <tr><td>this</td><td>works</td></tr>
  <tr><td>this</td><td>works</td></tr>
</table>
//here should the second table be and also the rest of the page (footer), this is completely missing

我做错了什么?谢谢!

您可能在kal_generator.php中定义了一个函数或类。当您尝试重新定义这样的函数或类时,PHP会中止。考虑将代码放入一个函数中,只包含该函数一次,然后运行该函数,而不是包含一个文件。

kal_test.php

<?php
require_once 'kal_generator.php';
kal_generator("14/09/2011");
kal_generator("21/09/2011");
?>

kal_generator.php

<?php
function kal_generator($vbl) {
    /**
     * Here, you should be creating $output
     */
    echo <<EOF
<table>
  <tr><th>bla</th><th>blabla</th></tr>
EOF;
    foreach ($output as $v1) {
        echo "<tr>";
        foreach ($v1 as $v2) {
            echo "<td>$v2</td>";
        }
        echo "</tr>'n";
    }
    echo "</table>'n";
}
?>