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

Web Technologies-I



                   Notes                 Example:


                                 <?php
                                 $x = 8;

                                 $y = 9;
                                 $total = 0;

                                 function getSum() {
                                 GLOBAL $x, $y, $total;
                                   $total = $x + $y;

                                   echo $x. ‘ + ‘. $y. ‘ = ‘. $total;
                                 }

                                 getSum();                         // 7 + 8 = 17
                                 echo ‘<br />’. $total;            // 17

                                 ?>
                                 By declaring $x and $y variables GLOBAL within the function, the values of these variables can
                                 be used inside the function.
                                 The $total variable being set as GLOBAL, all references to it, inside or outside function, refers to
                                 the same global version. Changing its value within the function will carry forward.
                                 The code above will output:

                                 7 + 8 = 17
                                 17

                                 4.3.2 Static Variables
                                 A static variable exists only in a local function scope, but it does not lose its value when program
                                 execution leaves this scope.
                                 Declaring a variable static makes its value to be remembered by a function for the next time it
                                 is called.

                                 To declare a variable static, place the keyword STATIC (or static) in front of the variable (or more
                                 variables separated by comma).

                                         Example:

                                 <?php

                                 function f_local() {
                                   $x = 0;
                                   echo ‘<br /> x = ‘. $x;

                                   $x++;
                                 }



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