Reputation: 23
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?
Upvotes: 1
Views: 246
Reputation: 57114
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.
Upvotes: 1
Reputation: 4611
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');
}
Upvotes: 4