Global variables and re-use

In general programming, globals are bad practice:

  • You can’t easily look at the use of a global in one place and see all the other uses, e.g. where it was set or will be read later.
  • You have many places to change the use of that variable if e.g. the use or format of it changes.
  • This makes it hard to make reliable changes to your code and to debug where/who set a global.
  • Other code could accidentally write over your variables.

However, WordPress is a huge piece of PHP code, and if you want to write code which accesses the same information in many different places all over WordPress, globals are a way to achieve this without writing complicated data structures, and plugins do use them to achieve this as other solutions can be much more complicated or unncessary

There are a few things you can do to make your use of globals as safe and bug-free as possible, here are a few suggestions:

  • Give your global a very unique and descriptive name. E.g. $mozboz_highscoreplugin_scores . This prevents possible conflicts where other code might accidetally overwrite your gglobal

  • Document the use of the global somewhere! E.g. at the top of your plugin describe what globals it uses and how

  • If you are a more advanced PHP programmer, you may want to try doing more clever things such as put all your variables inside a single global with an array, or even inside a class where you have much more control over the data and it may be easier to debug. For example:

    • Instead of:

      global $my_plugin_variable1;
      global $my_plugin_variable2;
      $foo = $my_plugin_variable1 + $my_plugin_variable2;
      
    • Try:

      global $my_plugin_datastore;
      $foo = $my_plugin_datastore['var1'] + my_plugin_datastore['var2']
      
  • Uses of classes and e.g. singletons is more advanced but may give you some benefit because it allows you wrap up and pass around all the functions as well as the variables in your plugin’s program. E.g. in the example given perhaps you want to be able to call test() from anywhere, and in this case it might be nice to be able to do this from anywhere:

    $myplugin_object = getPluginInstance();
    $foo = $myplugin_object->test();