2013-06-02 34 views
1

我有以下程序结构:PHP需要/ include文件

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'; 

出于某种原因,当我使用的功能要求header.php和footer.php我的变量$ a不会被回显。它工作正常,如果我使用header.php或footer.php自己。我不明白问题是什么。你认为这里的问题是什么?

回答

4

你的问题可能只是一个函数的作用域不会自动包含全局变量。尝试设置$a全球像global $a;,下面的例子为您get_header()功能:

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

3Q!现在看来只能使用全局。 – user2427932

1

使用包括内部的功能包括直接在该函数的代码。因此该变量是该函数中的一个本地可访问变量 - 它不在函数之外设置。

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

0

使您的变量为全球

global $ YourVar;