从 PHP 函数内部更改全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4127788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing a global variable from inside a function PHP
提问by Chris Bier
I am trying to change a variable that is outside of a function, from within a function. Because if the date that the function is checking is over a certain amount I need it to change the year for the date in the beginning of the code.
我正在尝试从函数内部更改函数外部的变量。因为如果函数检查的日期超过一定数量,我需要它更改代码开头日期的年份。
$var = "01-01-10";
function checkdate(){
if("Condition"){
$var = "01-01-11";
}
}
回答by Alin Purcaru
A. Use the globalkeyword to import from the application scope.
A. 使用global关键字从应用程序范围导入。
$var = "01-01-10";
function checkdate(){
global $var;
if("Condition"){
$var = "01-01-11";
}
}
checkdate();
B. Use the $GLOBALSarray.
B. 使用$GLOBALS数组。
$var = "01-01-10";
function checkdate(){
if("Condition"){
$GLOBALS['var'] = "01-01-11";
}
}
checkdate();
C. Pass the variable by reference.
C.通过引用传递变量。
$var = "01-01-10";
function checkdate(&$funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate($var);
回答by Buggabill
Just use the global
keyword like so:
只需global
像这样使用关键字:
$var = "01-01-10";
function checkdate(){
global $var;
if("Condition"){
$var = "01-01-11";
}
}
Any reference to that variable will be to the global one then.
对该变量的任何引用都将指向全局变量。
回答by Douglas Muth
All the answers here are good, but... are you sure you want to do this?
这里的所有答案都很好,但是……您确定要这样做吗?
Changing global variables from within functions is generally a bad idea, because it can very easily cause spaghetti code to happen, wherein variables are being changed all over the system, functions are interdependent on each other, etc. It's a real mess.
从函数内部更改全局变量通常是一个坏主意,因为它很容易导致意大利面条式代码发生,其中变量在整个系统中被更改,函数相互依赖等等。这真是一团糟。
Please allow me to suggest a few alternatives:
请允许我提出一些替代方案:
1) Object-oriented programming
1) 面向对象编程
2) Having the function return a value, which is assigned by the caller.
2) 让函数返回一个值,该值由调用者分配。
e.g. $var = checkdate();
例如 $var = checkdate();
3) Having the value stored in an array that is passed into the function by reference
3) 将值存储在通过引用传递给函数的数组中
function checkdate(&$values) { if (condition) { $values["date"] = "01-01-11"; } }
function checkdate(&$values) { if (condition) { $values["date"] = "01-01-11"; } }
Hope this helps.
希望这可以帮助。
回答by rizon
Try this pass by reference
试试这个通过引用传递
$var = "01-01-10";
function checkdate(&$funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate($var);
or Try this same as the above, keeping the function as same.
或尝试与上述相同,保持功能相同。
$var = "01-01-10";
function checkdate($funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate(&$var);