101

What is the utility of the global keyword?

Are there any reasons to prefer one method to another?

  • Security?
  • Performance?
  • Anything else?

Method 1:

function exempleConcat($str1, $str2)
{
  return $str1.$str2;
}

Method 2:

function exempleConcat()
{
  global $str1, $str2;
  return $str1.$str2;
}

When does it make sense to use global?

For me, it appears to be dangerous... but it may just be a lack of knowledge. I am interested in documented (e.g. with example of code, link to documentation...) technical reasons.

Thanks in advance!


Bounty

This is a nice general question about the topic, I (@Gordon) am offering a bounty to get additional answers. Whether your answer is in agreement with mine or gives a different point of view doesn't matter. Since the global topic comes up every now and then, we could use a good "canonical" answer to link to.

i alarmed alien
  • 8,984
  • 3
  • 23
  • 36
Pascal Qyy
  • 4,346
  • 4
  • 28
  • 43
  • 2
    have a look at this link : http://stackoverflow.com/questions/1557787/ There's a lot of related articles on the bottom right side of this page – JohnP Mar 02 '11 at 10:29
  • 1
    So, I can't read any pro-global keyword. **1)** Why it's here. **2)** Why people use it ? – Pascal Qyy Mar 05 '11 at 16:42
  • It's not a direct answer to your question but [please read this older SO question](http://stackoverflow.com/questions/1285700/what-are-some-good-tips-for-a-new-php-developer). – Ólafur Waage Mar 02 '11 at 10:29
  • @G.Qyy Why is there `goto`? Why do people use it? They don't use it (I hope at least) :P – PeeHaa Jan 14 '12 at 00:02
  • At the end of last year (Dec 14), somebody has downvote this question. I'm very interested to know why, because all point of view, including negatives ones, are interesting. In this case more than ever! I'll be very thankful for any clue about it. – Pascal Qyy Apr 11 '15 at 16:53
  • Possible duplicate of [Are global variables in PHP considered bad practice? If so, why?](http://stackoverflow.com/q/1557787/1255289) – miken32 Mar 11 '17 at 18:00

7 Answers7

163

Globals are evil

This is true for the global keyword as well as everything else that reaches from a local scope to the global scope (statics, singletons, registries, constants). You do not want to use them. A function call should not have to rely on anything outside, e.g.

function fn()
{
    global $foo;              // never ever use that
    $a = SOME_CONSTANT        // do not use that
    $b = Foo::SOME_CONSTANT;  // do not use that unless self::
    $c = $GLOBALS['foo'];     // incl. any other superglobal ($_GET, …)
    $d = Foo::bar();          // any static call, incl. Singletons and Registries
}

All of these will make your code depend on the outside. Which means, you have to know the full global state your application is in before you can reliably call any of these. The function cannot exist without that environment.

Using the superglobals might not be an obvious flaw, but if you call your code from a Command Line, you don't have $_GET or $_POST. If your code relies on input from these, you are limiting yourself to a web environment. Just abstract the request into an object and use that instead.

In case of coupling hardcoded classnames (static, constants), your function also cannot exist without that class being available. That's less of an issue when it's classes from the same namespace, but when you start mix from different namespaces, you are creating a tangled mess.

Reuse is severly hampered by all of the above. So is unit-testing.

Also, your function signatures are lying when you couple to the global scope

function fn()

is a liar, because it claims I can call that function without passing anything to it. It is only when I look at the function body that I learn I have to set the environment into a certain state.

If your function requires arguments to run, make them explicit and pass them in:

function fn($arg1, $arg2)
{
    // do sth with $arguments
}

clearly conveys from the signature what it requires to be called. It is not dependent on the environment to be in a specific state. You dont have to do

$arg1 = 'foo';
$arg2 = 'bar';
fn();

It's a matter of pulling in (global keyword) vs pushing in (arguments). When you push in/inject dependencies, the function does not rely on the outside anymore. When you do fn(1) you dont have to have a variable holding 1 somewhere outside. But when you pull in global $one inside the function, you couple to the global scope and expect it to have a variable of that defined somewhere. The function is no longer independent then.

Even worse, when you are changing globals inside your function, your code will quickly be completely incomprehensible, because your functions are having sideeffects all over the place.

In lack of a better example, consider

function fn()
{
    global $foo;
    echo $foo;     // side effect: echo'ing
    $foo = 'bar';  // side effect: changing
}

And then you do

$foo = 'foo';
fn(); // prints foo
fn(); // prints bar <-- WTF!!

There is no way to see that $foo got changed from these three lines. Why would calling the same function with the same arguments all of a sudden change it's output or change a value in the global state? A function should do X for a defined input Y. Always.

This gets even more severe when using OOP, because OOP is about encapsulation and by reaching out to the global scope, you are breaking encapsulation. All these Singletons and Registries you see in frameworks are code smells that should be removed in favor of Dependency Injection. Decouple your code.

More Resources:

Community
  • 1
  • 1
Gordon
  • 296,205
  • 68
  • 508
  • 534
  • 11
    Why PHP implement such things? Is there an utility? I always surprised by dangerous implementations in PHP that a lot of people use every-time... It's hard form me to believe there are no logical reasons! – Pascal Qyy Mar 05 '11 at 16:40
  • 7
    I wish you could make *Globals are evil* larger. – Kermit Apr 17 '13 at 23:22
  • 3
    Wow, finally someone explained well why globals are evil... I always heard they were and I saw some very very specific examples as to why but this is really a good and comprehensive explanation for the general reason why. +1 – Wingblade Aug 27 '13 at 02:58
  • I'm really late, and I kind of understand what you're saying, but how about mysqli connections? Should those be passed as a parameter each time, or is a global $link; allowed in your eyes? – Mave Oct 13 '13 at 13:13
  • @Mave initialize the connection once in your bootstrap, then pass the connection to the constructor of a [TableDataGateway](http://martinfowler.com/eaaCatalog/tableDataGateway.html) or similar layer of abstraction that makes use of it. Then only use the abstraction. Consider this example code: http://stackoverflow.com/questions/13048252/multiple-functions-is-one-big-function-in-php/13048947#13048947 – Gordon Oct 13 '13 at 14:33
  • For the most part, `global` is evil. However, in the case of an anonymous function that provides no other means of gaining access to a parameter (such as one serving as the callback to a native method like `array_filter`) using `global` is the only option outside of a) creating an object or b) using `use ()` in PHP > 5.3 – crush Jan 23 '14 at 22:06
  • @crush so create an object or use `use` ;) – Gordon Jan 24 '14 at 08:26
  • Globals are great for non-open-source applications you are selling, and other situations where you do not want to ever use the code for anything else. I suppose this supports the sentiment that they are evil.. – zoltar Apr 25 '14 at 23:34
  • 2
    You're right, except for the constants. They do not represent a "state" of the application and it's ok to refer to them from within a function. The function does not "lie" if it's using a constant from the inside. I agree that it implies that the programmer at one point had knowledge of the outside, but that's a very acceptable trade off for what a constant is. Also, seriously, it's not too big of a deal. – Sebas Feb 13 '16 at 05:48
  • @Sebas yes, most of what we do is trade offs and I agree that a userland constant is not as severe as a global variable, because of it's immutable state. But it's global state nevertheless. It's better to encapsulate them. Regarding class constants, the issue is solely on efferent coupling, e.g. when you consume them in code not in the same namespace/package you are creating a dependency on the defining code. Also, you are effectively making the constant part of the public API and cannot change or remove it without risking BC breaks. The latter is also true for global constants. – Gordon Feb 13 '16 at 13:35
  • @Gordon Hi Gordon. All that makes sense. How come then I have access to static constants in famous java libraries? For example I could think of constants supposed to replace hard coded property names etc. They are available across packages, and won't break compatibility if api developers change their content. I think what's an anti pattern is using the constant's inner value outside of the api, isn't it? I'm kind of trying to see how I could replace them right now, but I'm not sure the problems you mention are an issue unless under specific conditions. – Sebas Feb 13 '16 at 18:20
  • @Sebas famous doesn't equal good design. Some coupling will not hurt you until it hurts you, so if it's not hampering reuse and maintainability in your code now, don't bother to change it. Like you said: it's a trade off. – Gordon Feb 14 '16 at 15:10
  • @Gordon, maybe this is old but I hope I'll get answer from you. Let's say we have 10 functions, all of them uses $db as an argument, if the $db variable name changes we would have to change that name in every of those function calls arguments? Same would be with if we used global keyboard instead of arguments. Both ways names would have to be changed, just with global only in one function (where it's inside function code block) and with arguments in every call of the function (which could be like 10 calls vs 1 function code block to change). – Lukas Mar 19 '21 at 10:41
  • @Lukas variable names are local to the function. If you have a `function foo($x)` it doesn't matter how `$x` is named outside that function. So if you pass `$db` to it, it will be still be known as `$x` inside the function. However, if you use `global $db` and rename the global variable name, you will also have to change the variable within the function or the lookup will fail. – Gordon Mar 22 '21 at 13:07
36

Globals are unavoidable.

It is an old discussion, but I still would like to add some thoughts because I miss them in the above mentioned answers. Those answers simplify what a global is too much and present solutions that are not at all solutions to the problem. The problem is: what is the proper way to deal with a global variable and the use of the keyword global? For that do we first have to examine and describe what a global is.

Take a look at this code of Zend - and please understand that I do not suggest that Zend is badly written:

class DecoratorPluginManager extends AbstractPluginManager
{
/**
 * Default set of decorators
 *
 * @var array
 */
protected $invokableClasses = array(
    'htmlcloud' => 'Zend\Tag\Cloud\Decorator\HtmlCloud',
    'htmltag'   => 'Zend\Tag\Cloud\Decorator\HtmlTag',
    'tag'       => 'Zend\Tag\Cloud\Decorator\HtmlTag',
   );

There are a lot of invisible dependencies here. Those constants are actually classes. You can also see require_once in some pages of this framework. Require_once is a global dependency, hence creating external dependencies. That is inevitable for a framework. How can you create a class like DecoratorPluginManager without a lot of external code on which it depends? It can not function without a lot of extras. Using the Zend framework, have you ever changed the implementation of an interface? An interface is in fact a global.

Another globally used application is Drupal. They are very concerned about proper design, but just like any big framework, they have a lot of external dependencies. Take a look at the globals in this page:

/**
 * @file
 * Initiates a browser-based installation of Drupal.
 */

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

/**
 * Global flag to indicate that site is in installation mode.
 */
define('MAINTENANCE_MODE', 'install');

// Exit early if running an incompatible PHP version to avoid fatal errors.
if (version_compare(PHP_VERSION, '5.2.4') < 0) {
  print 'Your PHP installation is too old. Drupal requires at least PHP 5.2.4. See the     <a     href="http://drupal.org/requirements">system requirements</a> page for more     information.';
  exit;
}

// Start the installer.
require_once DRUPAL_ROOT . '/includes/install.core.inc';
install_drupal();

Ever written a redirect to the login page? That is changing a global value. (And then are you not saying 'WTF', which I consider as a good reaction to bad documentation of your application.) The problem with globals is not that they are globals, you need them in order to have a meaningful application. The problem is the complexity of the overall application which can make it a nightmare to handle. Sessions are globals, $_POST is a global, DRUPAL_ROOT is a global, the includes/install.core.inc' is an unmodifiable global. There is big world outside any function that is required in order to let that function do its job.

The answer of Gordon is incorrect, because he overrates the independence of a function and calling a function a liar is oversimplifying the situation. Functions do not lie and when you take a look at his example the function is designed improperly - his example is a bug. (By the way, I agree with this conclusion that one should decouple code.) The answer of deceze is not really a proper definition of the situation. Functions always function within a wider scope and his example is way too simplistic. We will all agree with him that that function is completely useless, because it returns a constant. That function is anyhow bad design. If you want to show that the practice is bad, please come with a relevant example. Renaming variables throughout an application is no big deal having a good IDE (or a tool). The question is about the scope of the variable, not the difference in scope with the function. There is a proper time for a function to perform its role in the process (that is why it is created in the first place) and at that proper time may it influence the functioning of the application as a whole, hence also working on global variables. The answer of xzyfer is a statement without argumentation. Globals are just as present in an application if you have procedural functions or OOP design. The next two ways of changing the value of a global are essentially the same:

function xzy($var){
 global $z;
 $z = $var;
}

function setZ($var){
 $this->z = $var;
}

In both instances is the value of $z changed within a specific function. In both ways of programming can you make those changes in a bunch of other places in the code. You could say that using global you could call $z anywhere and change there. Yes, you can. But will you? And when done in inapt places, should it then not be called a bug?

Bob Fanger comments on xzyfer.

Should anyone then just use anything and especially the keyword 'global'? No, but just like any type of design, try to analyze on what it depends and what depends on it. Try to find out when it changes and how it changes. Changing global values should only happen with those variables that can change with every request/response. That is, only to those variables that are belonging to the functional flow of a process, not to its technical implementation. The redirect of an URL to the login page belongs to the functional flow of a process, the implementation class used for an interface to the technical implementation. You can change the latter during the different versions of the application, but should not change those with every request/response.

To further understand when it is a problem working with globals and the keyword global and when not will I introduce the next sentence, which comes from Wim de Bie when writing about blogs: 'Personal yes, private no'. When a function is changing the value of a global variable in sake of its own functioning, then will I call that private use of a global variable and a bug. But when the change of the global variable is made for the proper processing of the application as a whole, like the redirect of the user to the login page, then is that in my opinion possibly good design, not by definition bad and certainly not an anti-pattern.

In retrospect to the answers of Gordon, deceze and xzyfer: they all have 'private yes'(and bugs) as examples. That is why they are opposed to the use of globals. I would do too. They, however, do not come with 'personal yes, private no'-examples like I have done in this answer several times.

Loek Bergman
  • 2,092
  • 17
  • 18
  • The Drupal code sample does not use globals, it uses constants. A very important difference is that a constant cannot be redefined once it has been defined. Also you can't just compare the functions `xyz` and `setZ`. The first changes global state, the second is a class method and only changes the state of the instance it was called on. – Arjan Jan 26 '14 at 22:17
  • @Arjen: if you search for the keyword global in Drupal 7.14, then will you get hundreds of hits. It is an old problem with public setters: you don't control the place where they are changed once you have made them public. It has been advised not to use them at all or to declare them private, so it can not be added later. – Loek Bergman Jan 27 '14 at 14:17
  • @Arjan: due to my error with the spelling of your name did you not receive any notification of my response to you. Now you will. :-) – Loek Bergman Jan 27 '14 at 16:19
  • @LoekBergman: There are about 400 hits for the word `global` in drupal 7.26 (which is the latest version), some of those hits are in comments and several others appear to be in code that has not been touched for years. I sure hope they won't use `global`s in drupal 8. – Arjan Jan 27 '14 at 23:54
  • @LoekBergman Please use setters and getters. It doesnt take much time to set up and allows others who are using your code and perhaps extending your classes to have more control. Once you make a parameter public thats it. you don't have the option to hide it later on. – mAsT3RpEE Feb 06 '14 at 15:08
  • @mAsT3RpEE: I have no problem with getters and setters, but with the idea that the use of a getter and setter avoids working with globals. Globals come in many different flavors in a programming language, not only by some variables. A class is a global too, because you can not reuse its name twice. If you have a public setter, can you know where it is called? Can you control where it is called? Can you know to which object the setter belongs? Can you know which implementation of the setter is used? Do I use getters and setters in my classes? In general: yes. By definition: no. – Loek Bergman Feb 20 '14 at 22:19
36

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.

deceze
  • 471,072
  • 76
  • 664
  • 811
  • 1
    I'm sorry, but why would I definitely want to rename `$db`? It's the PDO, passed around everywhere. Why would it be changed when I can update the connection information separately? – Casey Dwayne Jul 21 '14 at 16:21
  • 3
    @kcd Because one day you realize how great dependency injection is and want to restructure your app? Because one day you'll need to integrate your stuff with some other stuff that *also* uses a global `$db` variable? Because one day you'll discover unit testing and need to manage more than one database connection at a time for that? Many, many reasons. – deceze Jul 21 '14 at 16:25
  • @deceze Let's say we have 10 functions, all of them uses $db as an argument, if the $db variable name changes we would have to change that name in every of those function calls arguments? Same would be if we used global keyboard instead of arguments. Both ways names would have to be changed, just with global only in one function (where it's inside function code block) and with arguments in every call of the function (which could be like 10 calls vs 1 function code block to change). – Lukas Mar 19 '21 at 10:44
  • 1
    @Lukas The function defines its own argument name, e.g. `function foo($db) { ... }`. It accepts arguments *positionally*, i.e. the first argument passed to `foo(...)` will become `$db` inside it. It doesn't matter what the argument name is from the caller's side: `foo($base)`, `foo($connection)` or even `foo(new mysqli(...))`; all will end up as `$db` inside `foo`. If you rename the variable *in the caller's scope*, well, then you'll need to rename it there, **but that is localised to just the caller's scope**, which is the entire point. Passing values as function arguments decouples names. – deceze Mar 19 '21 at 11:06
  • Yes I understand that part, that inside the function the name wouldn't matter because any passed argument will be used with the function variable name inside, but where I'm stuck is, for example we CALL function getUsers($db); if the $db changes to $connectDb we will have to go and change that passing too from getUsers($db); to getUsers($connectDb): the "passing moment" is still dependent on the variable name. Maybe I'm missing something really important here, correct me if I do. I understand that this is easy to solve with OOP but I want to see solve in procedural way for learning purposes. – Lukas Mar 19 '21 at 11:22
  • 1
    @Lukas Yes, you are correct, if you rename a variable, then you need to rename it in every part of your code that references this variable. The trick is to limit the scope of your variables as much as possible, so there simply aren't that many places in your code that refer to the same variable. At most it's within one function, and functions should be kept as small as possible (if it's getting longer than a few dozen lines, perhaps break it into smaller functions); or it's one class with a property you need to rename, and you try to keep your classes as small as possible too. – deceze Mar 19 '21 at 11:26
  • 1
    @Lukas That's a bad argument for globals. Yes, in this particular example it's 1 vs 2 changes, but this amortises very quickly across *your entire codebase*. – deceze Mar 19 '21 at 11:35
  • @deceze speaking about spaghetti code, let's say I have function() {} in include1.php and in include2.php i call that function. Both of them are included in file main.php, is this considered bad practice? Because I want to separate function calling from function declaring in two different files and join them in one main file for readibility. Is this bad, could be done differently? Thanks for your time dealing with my questions. EDIT: i guess main problem in this scenario is that include2.php cannot work without include1.php, but then how to solve this problem? – Lukas Mar 19 '21 at 11:39
  • 1
    @Lukas It's okay to include functions from different files, even in multiple different files, even such that A uses B, and C uses both A and B, as long as you don't create irreconcilable circular dependencies. Each file should `include` the files it needs. Since PHP would produce errors if you `include` the same function definition twice, you'd use `require_once`, which is exactly for this purpose. Or you use auto-loading. – deceze Mar 19 '21 at 12:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230124/discussion-between-lukas-and-deceze). – Lukas Mar 19 '21 at 12:22
15

Simply put there is rarely a reason to global and never a good one in modern PHP code IMHO. Especially if you're using PHP 5. And extra specially if you're develop Object Orientated code.

Globals negatively affect maintainability, readability and testability of code. Many uses of global can and should be replaced with Dependency Injection or simply passing the global object as a parameter.

function getCustomer($db, $id) {
    $row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
    return $row;
}
xzyfer
  • 13,077
  • 5
  • 32
  • 45
9

Dont hesitate from using global keyword inside functions in PHP. Especially dont take people who are outlandishly preaching/yelling how globals are 'evil' and whatnot.

Firstly, because what you use totally depends on the situation and problem, and there is NO one solution/way to do anything in coding. Totally leaving aside the fallacy of undefinable, subjective, religious adjectives like 'evil' into the equation.

Case in point :

Wordpress and its ecosystem uses global keyword in their functions. Be the code OOP or not OOP.

And as of now Wordpress is basically 18.9% of internet, and its running the massive megasites/apps of innumerable giants ranging from Reuters to Sony, to NYT, to CNN.

And it does it well.

Usage of global keyword inside functions frees Wordpress from MASSIVE bloat which would happen given its huge ecosystem. Imagine every function was asking/passing any variable that is needed from another plugin, core, and returning. Added with plugin interdependencies, that would end up in a nightmare of variables, or a nightmare of arrays passed as variables. A HELL to track, a hell to debug, a hell to develop. Inanely massive memory footprint due to code bloat and variable bloat too. Harder to write too.

There may be people who come up and criticize Wordpress, its ecosystem, their practices and what goes on around in those parts.

Pointless, since this ecosystem is pretty much 20% of roughly entire internet. Apparently, it DOES work, it does its job and more. Which means its the same for the global keyword.

Another good example is the "iframes are evil" fundamentalism. A decade ago it was heresy to use iframes. And there were thousands of people preaching against them around internet. Then comes facebook, then comes social, now iframes are everywhere from 'like' boxes to authentication, and voila - everyone shut up. There are those who still did not shut up - rightfully or wrongfully. But you know what, life goes on despite such opinions, and even the ones who were preaching against iframes a decade ago are now having to use them to integrate various social apps to their organization's own applications without saying a word.

......

Coder Fundamentalism is something very, very bad. A small percentage among us may be graced with the comfortable job in a solid monolithic company which has enough clout to endure the constant change in information technology and the pressures it brings in regard to competition, time, budget and other considerations, and therefore can practice fundamentalism and strict adherence to perceived 'evils' or 'goods'. Comfortable positions reminiscent of old ages these are, even if the occupiers are young.

For the majority however, the i.t. world is an ever changing world in which they need to be open minded and practical. There is no place for fundamentalism, leave aside outrageous keywords like 'evil' in the front line trenches of information technology.

Just use whatever makes the best sense for the problem AT HAND, with appropriate considerations for near, medium and long term future. Do not shy away from using any feature or approach because it has a rampant ideological animosity against it, among any given coder subset.

They wont do your job. You will. Act according to your circumstances.

unity100
  • 767
  • 8
  • 16
  • 3
    +1 for anti-fundamentalism and so, but saying just "a lot of people use it / it work / etc" is just an "argumentum ad populum", a basic sophism. the fact a majority of people think or do one thing do not prove they're right! in a crowd, if a danger appear, the majority of people will do stupid things, and a some people will die stomped by others. Are they right to put their foot on the face of this five years old little girl just because they think they must absolutely push a door who open only if it is pulled to escape the fire? I don't think so… – Pascal Qyy Oct 02 '14 at 14:40
  • 1
    majority doing something of course does not validate anything by itself. however, the case is software. and if majority is doing it, and a majority of the apps and services created by these people are holding well (wordpress to many others) then it means that they can be used. – unity100 Oct 02 '14 at 20:00
6

I think everyone has pretty much expounded on the negative aspects of globals. So I will add the positives as well as instructions for proper use of globals:

  1. The main purpose of globals was to share information between functions. back when there was nothing like a class, php code consisted of a bunch of functions. Sometimes you would need to share information between functions. Typically the global was used to do this with the risk of having data corrupted by making them global.

    Now before some happy go lucky simpleton starts a comment about dependency injection I would like to ask you how the user of a function like example get_post(1) would know all the dependencies of the function. Also consider that dependencies may differ from
    version to version and server to server. The main problem with dependency injection is dependencies have to be known beforehand. In a situation where this is not possible or unwanted global variables were the only way to do achieve this goal.

    Due to the creation of the class, now common functions can easily be grouped in a class and share data. Through implementations like Mediators even unrelated objects can share information. This is no longer necessary.

  2. Another use for globals is for configuration purposes. Mostly at the beginning of a script before any autoloaders have been loaded, database connections made, etc.

    During the loading of resources, globals can be used to configure data (ie which database to use where library files are located, the url of the server etc). The best way to do this is by use of the define() function since these values wont change often and can easily be placed in a configuration file.

  3. The final use for globals is to hold common data (ie CRLF, IMAGE_DIR, IMAGE_DIR_URL), human readable status flags (ie ITERATOR_IS_RECURSIVE). Here globals are used to store information that is meant to be used application wide allowing them to be changed and have those changes appear application wide.

  4. The singleton pattern became popular in php during php4 when each instance of an object took up memory. The singleton helped to save ram by only allowing one instance of an object to be created. Before references even dependancy injection would have been a bad idea.

    The new php implementation of objects from PHP 5.4+ takes care of most of these problems you can safely pass objects around with little to no penalty any more. This is no longer necessary.

    Another use for singletons is the special instance where only one instance of an object must exist at a time, that instance might exist before / after script execution and that object is shared between different scripts / servers / languages etc. Here a singleton pattern solves the solution quite well.

So in conclusion if you are in position 1, 2 or 3 then using a global would be reasonable. However in other situations Method 1 should be used.

Feel free to update any other instances where globals should be used.

mAsT3RpEE
  • 1,650
  • 1
  • 16
  • 14
6

It makes no sense to make a concat function using the global keyword.

It's used to access global variables such as a database object.

Example:

function getCustomer($id) {
  global $db;
  $row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
  return $row;
}

It can be used as a variation on the Singleton pattern

Bob Fanger
  • 24,735
  • 7
  • 52
  • 70