简体   繁体   中英

PHP include var from file in a file that is then included in other files

I have a blog structured with several different php files (header, footer, main, etc.). I want to create a PHP file called adv.php that contains a var that needs to be retrieved in all the other PHP files. I would like to include the adv.php file ONLY in the header.php, and make sure that the var still works in footer.php, main.php, and so on.

I tried and even with global vars, this doesn't seem to work. How can I fix this? Again, I would like to only include the adv.php file once in header.php and not in every single php file.

EDIT

Here is a simplified version of the code with only relevant parts:

adv.php

<?php $ad300_top_right_index = "RTB"; ?>

header.php

<?php include_once('adv.php');  ?>

main.php

<?php if  ( $ad300_top_right_index == "RTB" ) { ?>

show code here

<?php } else { ?>

show some other code here

<?php } ?>

About the inclusions: it's a Wordpress template, where the resulting page will include header.php and main.php, and header.php includes adv.php. Of course adv.php gets included before I try to use the var in main.php.

You haven't shown any code, but there is NO reason for a var included in one file to not be visible in the other:

a.php

<?php
$x = 7;

b.php

<?php
echo $x, "\n";

z.php

<?php
echo "#1 - startup\n";
echo $x, "\n";

echo "#2 - including a\n";
include('a.php');

echo "#3 - included\n";
echo $x, "\n";

echo "#4 - including b\n";
include('b.php');

echo "#5 - included\n";

Output of running z.php:

#1 - startup
PHP Notice:  Undefined variable: x in /home/marc/z.php on line 3

#2 - including a
#3 - included
7
#4 - including b
7
#5 - included

Note that 7 is output as expected.

If you're not getting your var, then there's something OTHER than php causing the problem, eg not understanding scoping rules.

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