1

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?

3 Answers 3

4

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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

3Q!It now appears that only use global.
1

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.

Comments

0

make your variable As Global

global $YourVar;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.