简体   繁体   English

PHP将文件中的var包含在一个文件中,然后将其包含在其他文件中

[英]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.). 我有一个博客,结构中包含几个不同的php文件(页眉,页脚,主要等)。 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. 我想创建一个名为adv.php的PHP文件,其中包含需要在所有其他PHP文件中检索的var。 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. 我只想将adv.php文件包括在header.php中,并确保var仍可在footer.php,main.php等中使用。

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. 同样,我只想将adv.php文件包含在header.php中,而不是包含在每个php文件中。

EDIT 编辑

Here is a simplified version of the code with only relevant parts: 这是仅包含相关部分的代码的简化版本:

adv.php adv.php

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

header.php header.php

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

main.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. 关于内含物:这是一个Wordpress模板,其结果页面将包含header.php和main.php,而header.php包含adv.php。 Of course adv.php gets included before I try to use the var in main.php. 当然,在尝试使用main.php中的var之前,必须先包含adv.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: 您没有显示任何代码,但是没有理由使一个文件中包含的var在另一个文件中不可见:

a.php a.php

<?php
$x = 7;

b.php b.php

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

z.php 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: 运行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. 请注意,将按预期输出7

If you're not getting your var, then there's something OTHER than php causing the problem, eg not understanding scoping rules. 如果您没有获得var,则可能是php以外的其他原因导致该问题,例如,不了解范围规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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