Scope and the global Statement PHP

As discussed earlier, variables inside a function exist inside a name space separate from the global name space. Variables inside a function are private property and may never be seen or manipulated outside the function. However, there are two ways a function may access variables in the global scope: the global statement and the GLOBALS array.

The global statement brings a variable into a function's name space. Thereafter the variable may be used as if it were outside the function. Any changes to the variable will persist after execution of the function ceases. In the same way, it is possible to refer to global variables through the array GLOBALS. The array is indexed by variable names, so if you create a variable named userName you can manipulate it inside a function by writing $GLOBALS["userName"].

If a variable is declared to be static, it retains its value between function calls. demonstrates the use of static variables.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics