WordPress是否清除$ GLOBALS? [英] Does WordPress clear $GLOBALS?

查看:159
本文介绍了WordPress是否清除$ GLOBALS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是在Word Press主题中包含我的一个PHP脚本。问题是,在包含脚本文件后,我无法在主题文件的函数内访问脚本文件中声明的变量。

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 .

我创建了一个新的文件在主题文件夹中,并添加与header.php相同的代码,如果我打开该文件,它的工作原理就好了。所以,据我可以告诉它是Word Press相关的东西。

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

内容:/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;

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

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


推荐答案

我并没有推广使用 $ GLOBALS ,但无论如何...使用以下方式定义变量:

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.

这篇关于WordPress是否清除$ GLOBALS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆