1

我有一个 paging.php 文件,它有一个函数latest($imagesPerPage, $site) {.

在该函数内部,我有一个变量 $lastPage:

$catResult->data_seek(0); 
$totalComics = 0;
while ($row = $catResult->fetch_assoc()) {
    $totalComics++;
}

global $lastPage;
$lastPage = ceil($totalComics/$imagesPerPage);

我有另一个文件 homepage.php,它需要使用$lastPage上面定义的 paging.php 文件的“latest()”函数。


在 homepage.php 的顶部,我包含了页面文件:include 'scripts/paging.php';

然后我打电话<?php echo latest(15, $site); ?>显示一些图像......

下面,我要处理页码和导航,需要使用 $lastPage 变量:

    for($i = 1; $i <= $lastPage; $i++) {
        echo '<li><span class=navItems><a href="?site=' . $site . '&cat=' . $cat . '&page=' . $i .'">' . $i . '</a></span></li>';
    }

homepage.php 一直抱怨 $lastPage 未定义...我试过了global $lastPage$GLOBALS[$lastPage]...但它仍然不可用。


我的问题是:

  1. 我怎样才能使$lastPage函数之外的 homepage.php 文件可用?

  2. 如何使$lastPagepaging.php 中的其他功能可用?

4

1 回答 1

3

您需要做的就是包含包含该函数的文件。

如果该文件包含您不想包含在其他文件中的其他代码,则制作一个函数文件;专用于住房功能的文件,您可以将其包含在其他页面中。

看看PHP 的 include 函数

例如,如果您的函数位于名为的文件中functions.inc.php

include("functions.inc.php");

// Here you can use the function

关于$lastPage无法访问的变量,请尝试以下操作:

// Inside imageDisplay.php -- OUTSIDE OF THE FUNCTION ---
$lastPage = "Whatever it's value needs to be"; // If we declare it outside the function we can use it on any page which includes this file

function paging() {
    global $lastPage; // This now means you can use the $lastPage variable inside the function
    ...
}

希望这有助于解释如何$lastPage在函数外部、包含的页面以及函数内部使用变量。

于 2013-02-11T16:59:50.293 回答