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

时间:2011-09-13 13:56:05

标签: php include

我有一个名为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

我做错了什么? 谢谢!

1 个答案:

答案 0 :(得分:14)

您可能在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";
}
?>