1

我有以下程序结构:

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:页脚.php:

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

由于某种原因,当我使用函数来要求 header.php 和 footer.php 我的变量 $a 没有得到回显。如果我单独使用 header.php 或 footer.php,它工作正常。我不明白问题是什么。你认为这里的问题是什么?

4

3 回答 3

4

您的问题可能只是函数的范围不会自动包含全局变量。尝试设置$a为 global like global $a;,以下示例为您的get_header()功能:

function get_header(){
    global $a; // Sets $a to global scope
    require('./tpl/header.php');
}
于 2013-06-02T14:47:26.163 回答
1

在函数内使用 include 会将代码直接包含在该函数中。因此,该变量是该函数可访问变量的本地变量 - 它未在函数外部设置。

如果您需要/包含没有函数,则 $a 将成为全局变量。

于 2013-06-02T14:48:15.497 回答
0

使您的变量成为全局变量

全球 $YourVar;

于 2013-06-02T14:55:53.863 回答