Page 112 - Open Soource Technologies 304.indd
P. 112

Unit 7: Functions



            A global keyword also enables you to declare what global variables you want to access, causing   Notes
            them to be imported into the function’s scope. However, using this keyword is not recommended
            for various reasons, such as misbehaving with assigning values by reference, not supporting
            unset ( ), and soon.

                    Here’s a short description of it—but please, don’t use it!
                    The syntax is

            global $var1, $var2, ...;

            Adding a global line for the previous example results in the following:
                  Example:         function func()

                                          {

                                                         global $var;
                                                          $var = 2;

                                           }
                                          $var = 1;

                                          func( );

                                          print $var;
            This way of writing the example also prints the number 2.

            7.3 Returning Values By Value


            You can tell from the previous example that the return statement is used to return values from
            functions. The return statement returns values by value, which means that a copy of the value
            is created and is returned to the caller of the function.
                  Example:                 function get_global_variable_value($name)

                                               {
                                                         return $GLOBALS[$name];
                                                  }

                                                   $num = 10;
                                                  $value = get_global_variable_value(“num”);

                                                  print $value;
            This code prints the number 10. However, making changes to $value before the print statement
            only affects $value and not the global variable $num. This is because its value was returned by
            the get_global_variable_value ( ) by value and not by reference.

            7.4 Returning Values By Reference


            PHP also allows you to return variables by reference. This means that you’re not returning a
            copy to the variable, but you’re returning the address of your variable instead, which enables


                                             LOVELY PROFESSIONAL UNIVERSITY                                   107
   107   108   109   110   111   112   113   114   115   116   117