douchuituo3032 2010-04-27 11:43
浏览 56
已采纳

WordPress清除$ GLOBALS吗?

What I want to do is to include one of my PHP scripts in a Word Press theme. The problem is that after I include the script file I can't access, inside functions in the theme file, variables declared in the script file .

I have created a new file in the theme folder and added the same code as in header.php and if I open that file it works just fine. So as far as I can tell it's something Word Press related.

/other/path/wordpress/wp-content/themes/theme-name/header.php // this is broken
/other/path/wordpress/wp-content/themes/theme-name/test.php   // this works

/var/www/vhosts/domain/wordpress/ ->(symlink)-> /other/path/wordpress/
                                                /other/path/wordpress/wp-content/themes/theme-name/header.php
/var/www/vhosts/domain/include_file.php

Content of: /var/www/vhosts/domain/include_file.php

$global_var = 'global';
print_r($GLOBALS);  // if I open this file directly this prints globals WITH $global_var;
                    // if this file is included in header this prints all the WP stuff WITHOUT $global_var;

Content of: /other/path/wordpress/wp-content/themes/theme-name/header.php require '/path/to/include_file.php';

print $global_var; // this prints 'global' as expected
function test()
{
    global $global_var;
    print $global_var; // this is NULL
}
test();
print_r($GLOBALS); // this prints all the WP stuff WITHOUT $global_var in it
  • 写回答

1条回答 默认 最新

  • dongrong9938 2010-04-27 14:40
    关注

    I'm not promoting the use of $GLOBALS, but anyway... define your variable using:

    $GLOBALS['varname'] = 'value';
    

    That should work. I suspect you're not actually in global scope like you think you are. That file is probably being include by a function, in which case you're in function-scope.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)