Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a global variable from inside a function 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";       } } 
like image 315
Chris Bier Avatar asked Nov 08 '10 20:11

Chris Bier


People also ask

How do I change a global variable inside a function?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

How can use global variable inside function in PHP?

Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

What is $_ global in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.


1 Answers

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); 
like image 81
Alin Purcaru Avatar answered Oct 03 '22 20:10

Alin Purcaru