PHP require/include file


PHP require/include file

我有以下程序结构:

Root directory:-----index.php
                       |-------TPL directory
                                 |-------------header.php
                                 |-------------index.php
                                 |-------------footer.php
php file loading structure:
Root directory:index.php ----require/include--->tpl:index.php
                                                      |----require/include-->header.php
                                                      |----require/include-->footer.php

根目录index.php:

    <?php
function get_header(){
    require('./tpl/header.php');
}
function get_footer(){
    require('./tpl/footer.php');
}
$a = "I am a variable";

要求('。tpl/index . php ');

TPL: index . php:

    <?php
get_header();//when I change require('./tpl/header.php'); variable $a can work!!
echo '<br />';
echo 'I am tpl index.php';
echo $a;
echo '<br />';
get_footer();//when I change require('./tpl/footer.php'); variable $a can work!!

TPL: header。php:

    <?php
echo 'I am header.php';
echo $a;//can not echo $a variable
echo '<br/>';

TPL: footer。php:

    <?php
echo '<br />';
echo $a;//can not echo $a variable
echo 'I am footer';

由于某些原因,当我使用function来要求header.php和footer.php时,变量$a没有得到回显。如果我单独使用header。php或footer。php,它可以正常工作。我不明白问题出在哪里。你觉得问题出在哪里?

您的问题可能只是函数的作用域没有自动包含全局变量。尝试将$a设置为全局,就像global $a;一样,下面是get_header()函数的示例:

function get_header(){
    global $a; // Sets $a to global scope
    require('./tpl/header.php');
}

在函数中使用include将代码直接包含在该函数中。因此,该变量是该函数可访问的局部变量——它不是在函数外部设置的。

如果你的require/include中没有一个函数,$a就会变成一个全局变量。

将变量设为全局

全球YourVar美元;