- PHP: Global variables do not have scope inside functions (unless you use the keyword ‘
global‘ preceding the global variable being referenced inside the function to access them). Variables inside functions, conversely, do not have global scope and are not visible outside of their parent function (you can declare a variable inside a function as global by again using the keyword ‘
There is an excellent post on Stackoverflow here discussing variable scope in PHP in great detail.
A key ‘quirk’ to note that might be confusing is to understand that, in PHP, if a variable inside a function is created and declared as global without having existed as a global beforehand, then it’s value will only be retained inside that function, and outside of the function it will be empty. If the global variable has already been declared in the global space, then referencing it inside a function with the ‘
global‘ keyword will allow you to assign it a value that sticks globally.