从函数PHP中更改全局变量 [英] Changing a global variable from inside a function PHP

查看:119
本文介绍了从函数PHP中更改全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个函数内改变一个函数之外的变量。因为如果函数检查的日期超过了一定数量,我需要它在代码的开始处更改日期的年份。

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";
      }
}


推荐答案

A 。使用全球关键字从应用范围导入。

A. Use the global keyword to import from the application scope.

$var = "01-01-10";
function checkdate(){
    global $var;  
    if("Condition"){
        $var = "01-01-11";
    }
}
checkdate();



B。使用 $ GLOBALS 数组。

$var = "01-01-10";
function checkdate(){
    if("Condition"){
        $GLOBALS['var'] = "01-01-11";
    }
}
checkdate();

C。通过引用传递变量

C. Pass the variable by reference.

$var = "01-01-10";
function checkdate(&$funcVar){  
    if("Condition"){
        $funcVar = "01-01-11";
    }
}
checkdate($var);

这篇关于从函数PHP中更改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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