簡體   English   中英

在功能文件末尾包含模板PHP文件

[英]Including template PHP file at the end of functions file

我正在用書學習基本的PHP。 在書中,我完成了以下示例:

<?php
session_start()

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";

本書中使用了“ functions.php”文件末尾的“ include template.php”,它似乎可以正常工作。 但是,在我的示例中使用時,用於顯示結果的template.php無法正常工作,這是使用PHP代碼的template.php部分:

<table>
            <tr>
                <th>Tasks</th>
            </tr>
            <?php foreach($taskList as $task) : ?>
            <tr>
                <td><?=$task?></td>
            </tr>
            <?php endforeach; ?>
        </table>

這里顯示的錯誤:

Notice: Undefined variable: taskList in C:\xampp\htdocs\to-do-list\template.php on line 27

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\to-do-list\template.php on line 27

以我的理解,template.php並沒有像其所獲得的那樣從functions.php獲取信息。

PHP文檔

上面的文檔中有以下示例:

<?php
$a = 1;
include 'b.inc';
?>

因此,b.inc將具有$ a var。 這本書中發生的事情是一樣的。

您的示例工作正常,但是由於我無法考慮從問題的確切位置入手,因此我建議

這是我嘗試並調用帶有和不帶有參數的functions.php的確切代碼,並且工作正常

的functions.php

<?php

session_start();

if(array_key_exists("taskName", $_GET)) {
    $_SESSION["taskList"][] = $_GET["taskName"];
}

$taskList= [];

if(array_key_exists("taskList", $_SESSION)) {
    $taskList = $_SESSION["taskList"];
}

include "template.php";

的template.php

<table>
    <tr>
        <th>Tasks</th>
    </tr>
        <?php foreach($taskList as $task) : ?>
            <tr>
                <td><?=$task?></td>
            </tr>
        <?php endforeach; ?>
</table>

當我嘗試下面的代碼時,它可以在我的計算機上正常工作(它會產生一些輸出)。

檔案:first.php

<?php
$taskList = [];
$taskList[]=5;
$taskList[]=6;
include 'second.php';
?>

檔案:second.php

<table>
  <tr>
    <th>Tasks</th>
  </tr>
  <?php foreach($taskList as $task) : ?>
    <tr>
      <td><?=$task?></td>
    </tr>
  <?php endforeach; ?>
</table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM