Changing a global variable from inside a function PHP

Chris Bier picture Chris Bier · Nov 8, 2010 · Viewed 79.1k times · Source

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

Answer

Alin Purcaru picture Alin Purcaru · Nov 8, 2010

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. Use the $GLOBALS array.

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

C. Pass the variable by reference.

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