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.

    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上