What is the utility of the global keyword?
Are there any reasons to prefer one method to another?
The one big reason against global
is that it means the function is dependent on another scope. This will get messy very quickly.
$str1 = 'foo';
$str2 = 'bar';
$str3 = exampleConcat();
vs.
$str = exampleConcat('foo', 'bar');
Requiring $str1
and $str2
to be set up in the calling scope for the function to work means you introduce unnecessary dependencies. You can't rename these variables in this scope anymore without renaming them in the function as well, and thereby also in all other scopes you're using this function. This soon devolves into chaos as you're trying to keep track of your variable names.
global
is a bad pattern even for including global things such as $db
resources. There will come the day when you want to rename $db
but can't, because your whole application depends on the name.
Limiting and separating the scope of variables is essential for writing any halfway complex application.