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

Unit 4: Functions



                   Example:                                                                       Notes


            <?php
            function test() {
              $x = 8;

              echo $x;
            }



            echo $x;             //

            test();              // 8
            ?>

            The “echo $x” expression outside the function returns an error because the $x variable is not
            defined or recognized outside the test() function, but the “echo” statement inside function refers
            to a local $x variable, which is defined within test() function.


            Another example:

            <?php
            $x = 8;


            function test() {
              echo $x;

            }



            echo $x;             // 8
            test();              //

            ?>
            This time, the $x variable is defined outside the function, but not inside it.

            As you can see, the calling function returns an error notice, because the “echo” statement refers
            to a local version of the $x variable, and it has not been assigned a value within this scope.

            4.3.1 Global Variables
            A global variable can be accessed in any part of the program.

            If you want to use inside a function a variable defined outside it, that variable must be explicitly
            declared to be global in the function. This is accomplished by placing the keyword GLOBAL (or
            global) in front of the variable that should be recognized as global (or more variables separated
            by comma). This will extends the scope of that variable inside the function.






                                             LOVELY PROFESSIONAL UNIVERSITY                                    81
   82   83   84   85   86   87   88   89   90   91   92