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"; } }
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.
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.
$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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With