简体   繁体   中英

PHP require/include file

I have the following program Structure:

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

Root index.php :

    <?php
function get_header(){
    require('./tpl/header.php');
}

function get_footer(){
    require('./tpl/footer.php');
}

$a = "I am a variable";

require('./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';

For some reason when I used function to require header.php and footer.php my variable $a doesn't get echoed. It works fine if I use header.php or footer.php on its own. I do not understand what the problem is. What do you think is the issue here?

Your issue is probably just scope of a function does not automatically include global variables. Try setting $a to global like global $a; , example below for your get_header() function:

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

Using the include inside a function includes the code directly in that function. Therefore the variable is a locally in that function accessable variable - it is not set outside the function.

If you require/include without a function $a becomes a global variable.

make your variable As Global

global $YourVar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM