I have some variables that I want to be globally available to all functions. I was under the impressions I could just say:

global $variable;
$variable = array('value1','value2');

outside the function and then any function can read that variable. However I was getting an error trying to use the variable in a foreach loop inside a function. I had to declare the variable as global inside the function to get it to work (even though the variable's values are set outside the function)

Say I have a dozen global variables. (They are site-wide configuration parameters) So are you telling me I have to declare them as global in each function that will use them as opposed to just declaring them global once outside the functions? That's kind lame (and a pain). There's got to be a better way.

    You will end up using a dozen global statements in each function or using $GLOBAL which is a pain

    Store your globals in an array or a class. The you need only one global per function. And your code will be better organized.

      Originally posted by jazee
      So are you telling me I have to declare them as global in each function that will use them as opposed to just declaring them global once outside the functions?

      Yes:

      The manual
      Example 7-1. Using global

      <?php
      $a = 1;
      $b = 2;
      
      function Sum()
      {
          global $a, $b;
      
      $b = $a + $b;
      } 
      
      Sum();
      echo $b;
      ?>
      

      The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

      That's kind lame (and a pain). There's got to be a better way.

      That is the better way and was a deliberate design decision; it's lame (and a pain) to go around writing stuff that uses dozens of global variables. Or at least, poor programming practice.

        The Academic In Me) Never use a global inside of a function it is bad form and makes your code ugly. It also causes lots of maintenence issues later on. Always use parameters for external information and just pass them properly to maintain changes or not.

        The Hacker In Me) I love globals they are my firends. Why should I bother passing stuff around when it wastes memory and causes problems now. I'll just use globals and let someone else worry about maintenence.

        The Professional Programmer) Globals should be used inside of functions sparingly. If if can be done with a parameter it should be. But if you're running out of time and it's quicker to use a global by all means do so.

          Originally posted by drawmack
          The Hacker In Me) I love globals they are my firends. Why should I bother passing stuff around when it wastes memory....

          Ah, but it doesn't. PHP uses reference counting and copy-on-write, so you can pass a 5MB array as a parameter and the only extra memory you consume is another slot in the symbol table.

            "That is the better way and was a deliberate design decision; it's lame (and a pain) to go around writing stuff that uses dozens of global variables. Or at least, poor programming practice."

            I think this statement is not necessarily valid as it is generalizing. As a general practice, it is of course valid. However, in the "real world" I believe there are many instances where use of globals is very appropriate. (Why would they have even included the function if it wasn't - duh)

            My particular case is a complex application that is ported to various websites. Globals help make the code extremely portable when you use them for master site configuration settings (site domain name, admin e-mail address, phone number, etc.) After a new update to the application is complete, I can go into one global declaration include file for each site's version and modify the parameters easily as opposed to doing search and replaces on all the code. Passing these values as parameters in every function that requires one or more of them is very impractical.

            I'm orignally a Perl programmer. While I like the fact the PHP is the opposite of Perl in that all variables are local unless specifically made global, in Perl, when you declare a local variable, it is accessible to anything below it (it cascades down). I think this functionally would be VERY useful in PHP but for globals. So that a global is accessible within the scope it is defined but is also accessible in a functions which are within that scope.

            With PHP, there are a variety of ways to pass the globals but all the ones proposed involve having to make a decleration within each function, or, adding some addition notation to all the variable names - $GLOBAL[variable_name] or $ANY_GLOBAL_ARRAY[variable_name]. If there are several different variables, referenced several times in a function, this is going to get messy.

            I'll stick to just putting a global statement at the beginning of each function that needs to access globals.

              Originally posted by jazee
              "That is the better way and was a deliberate design decision; it's lame (and a pain) to go around writing stuff that uses dozens of global variables. Or at least, poor programming practice."

              you're probably overlooking something.

              I think this statement is not necessarily valid as it is generalizing. As a general practice, it is of course valid. However, in the "real world" I believe there are many instances where use of globals is very appropriate. (Why would they have even included the function if it wasn't - duh)

              backwards compatibility --> duh why does c++ still include the goto command.

              My particular case is a complex application that is ported to various websites. Globals help make the code extremely portable when you use them for master site configuration settings (site domain name, admin e-mail address, phone number, etc.) After a new update to the application is complete, I can go into one global declaration include file for each site's version and modify the parameters easily as opposed to doing search and replaces on all the code. Passing these values as parameters in every function that requires one or more of them is very impractical.

              constants would accomplish the same thing and they would do so without the need for globals. But of course I'm wrong here, never mind that globals are faster and more efficient. Globals inside of a function make the code less portable because you cannot pull the function out of the environment it was written in, i.e. this particular application, and use it in another environment, i.e. your next application. This being the case overuse of globals will lead to extranious coding.

              I'm orignally a Perl programmer. While I like the fact the PHP is the opposite of Perl in that all variables are local unless specifically made global, in Perl, when you declare a local variable, it is accessible to anything below it (it cascades down). I think this functionally would be VERY useful in PHP but for globals. So that a global is accessible within the scope it is defined but is also accessible in a functions which are within that scope.

              I am also a originally a PERL programmer, look at my avatar. This leads to programming mistakes like the following:

              for($i=0;$i<100;$i++) {
                #some code
                some_function($var);
              } #end for
              
              #lots of code say 200+ and maybe contained in a seperate
              #file.
              
              sub some_function($) {
                #some setup code
                for($i=0;$i<50;$i++) {
                  #Process something iteratively
                } #end for
                #some more code
                return(@_[1]);
              }
              

              with the php system you would have to explicitly declar $i as a global inside of some_function for it to affect the $i in the main procedure where as in PERL this is not the case.

              With PHP, there are a variety of ways to pass the globals but all the ones proposed involve having to make a decleration within each function, or, adding some addition notation to all the variable names - $GLOBAL[variable_name] or $ANY_GLOBAL_ARRAY[variable_name]. If there are several different variables, referenced several times in a function, this is going to get messy.

              Not really. First of all if a function is referencing more then five globals it's not written properly and should be split into multiple functions. Second of all you can get around this by doing this in a globally included file:

              <?php
              //for each function do this
              $function_name_params = array(
                  'global_var_name' => $global_var
                  .....
              ):
              

              then you can just call each function with something like this:

              function_name($function_name_params);

              Is that so difficult.

              I'll stick to just putting a global statement at the beginning of each function that needs to access globals.

              Okay, but in six months when you're asking for help because of this I'm going to link you back to this post.

                My personal preference would be ahundiak's suggestion of creating a class. If these functions are all that much interrelated that they need to pass a dozen different variables about between each other, then those functions and variables are just crying out to be wrapped in a class{}. If only for the sake of a clean namespace or the potential to then use two of them at once.

                  Write a Reply...