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

查看:39
本文介绍了从 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.使用 global 关键字从应用范围导入.

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.传递变量通过引用.

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

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

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