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

gie*_*ops 5 php include

我有一个调用的php文件kal_test.php,它给变量赋值$vbl.在调用的文件中需要此变量,该文件kal_generator.php从该变量生成一个表(我将为您提供详细信息).它是这样的:


[kal_test.php]

<?php
$vbl = "14/09/2011";
include ("kal_generator.php");
?>
Run Code Online (Sandbox Code Playgroud)

[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>
Run Code Online (Sandbox Code Playgroud)

这个设置工作正常,但我不能让其中两个出现在同一页面上,如下所示:

[kal_test.php]

<?php
$vbl = "14/09/2011";
include ("kal_generator.php");
$vbl = "21/09/2011";
include ("kal_generator.php");
?>
Run Code Online (Sandbox Code Playgroud)

这将得到以下结果:

//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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢!

Lek*_*eyn 14

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

kal_test.php

<?php
require_once 'kal_generator.php';
kal_generator("14/09/2011");
kal_generator("21/09/2011");
?>
Run Code Online (Sandbox Code Playgroud)

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";
}
?>
Run Code Online (Sandbox Code Playgroud)