使变量对所有类,方法,函数和包含都可用,就像$ _POST一样 [英] make variable available to all classes, methods, functions and includes, just like $_POST
问题描述
这个问题似乎很简单,但是我在任何地方都找不到答案...
This question seems simple enough, but I can't find an answer anywhere...
在我的php脚本/文件的开头,我想创建一个变量.
At the beginning of my php script/file I want to create a variable.
$variable = 'this is my variable';
我希望此变量在整个脚本中可用,以便所有类,方法,函数,包含的脚本等都可以简单地将此变量称为$ variable.
I want this variable to be available within the entire script, so that all classes, methods, functions, included scripts, etc. can simple call this variable as $variable.
Class MyClass
{
public function showvariable()
{
echo $variable;
}
}
$ _ SESSION,$ _ POST,$ _ GET变量的行为都一样.我可以编写一个方法并使用$ _POST,它将起作用.但是,如果我使用在脚本开头定义的$ variable,它会显示注意:未定义的变量:...中的变量",当我编写函数而不是类方法时,它甚至会说出来.
The $_SESSION, $_POST, $_GET variables all behave like that. I can just write a method and use $_POST and it'll work. but if I use $variable, which I have defined at the beginning of my script, it says "Notice: Undefined variable: variable in ..." It even says it, when I write a function, rather than a class method...
我试图写
global $variable = 'this is my variable';
但是该脚本无法加载... "HTTP错误500(内部服务器错误):服务器尝试满足请求时遇到了意外情况."
But then the script wouldn't load... "HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request."
如何使变量真正像$ _POST这样可以全局访问?
我为什么需要这个?我专门计划将其用作表单令牌.在页面顶部,将表单令牌生成为$ token,在页面底部,将其存储在会话中.在处理任何表单之前,我会检查SESSION令牌是否与POST令牌匹配...而且由于我经常在页面上使用多种表单(在顶部导航中登录表单,在主体中注册表单),我只是想使其变得方便和在每种形式上调用$ token.有时我的formelements是由类或函数生成的,但它们无法识别该变量,并表示未定义.
Why would I need this? I specifically plan on using it as a form token. At the top of the page I generate my form token as $token, at the bottom of the page I store it in the session. Before handling any form I check if the SESSION token matches the POST token... And since I often have multiple forms on the page (login form in the top nav, and register form in the main body) i just wanna make it convenient and call $token on each form. Sometimes my formelements are generated by classes or functions, but they don't recognize the variable and say it's not defined.
推荐答案
我找到了... -.-我认为这很容易...
I found it... -.- I thought it would be easy enough...
我必须使用来调用变量
$GLOBALS['variable'];
终于找到了...终于... http://php.net/manual/en/reserved.variables.globals.php
Just found it... finally... http://php.net/manual/en/reserved.variables.globals.php
编辑,例如大约8个月后:
EDIT like 8 months later or so:
我刚刚了解了CONSTANTS!
I just learned about CONSTANTS!
define('name', 'value');
无法重新分配它们... 我想我也可以使用它! http://www.php.net/manual/zh/language.constants.php
They just can't be reassigned... I guess I could use that, too! http://www.php.net/manual/en/language.constants.php
这篇关于使变量对所有类,方法,函数和包含都可用,就像$ _POST一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!