douzi1350 2015-12-14 16:52
浏览 45

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

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.

  • 写回答

1条回答 默认 最新

  • douxi2670 2015-12-14 18:57
    关注

    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, "
    ";
    

    z.php

    <?php
    echo "#1 - startup
    ";
    echo $x, "
    ";
    
    echo "#2 - including a
    ";
    include('a.php');
    
    echo "#3 - included
    ";
    echo $x, "
    ";
    
    echo "#4 - including b
    ";
    include('b.php');
    
    echo "#5 - included
    ";
    

    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, e.g. not understanding scoping rules.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab