PHP Functions Accessing a Global Variable Inside a Function - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Functions Accessing a Global Variable Inside a Function - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, May 24, 2019

PHP Functions Accessing a Global Variable Inside a Function

PHP Functions





Accessing a Global Variable Inside a Function


Problem

You need to access a global variable inside a function.

Solution

Bring the global variable into local scope with the global keyword:

          function eat_fruit($fruit) {
                 global $chew_count;
           
                 for ($i = $chew_count; $i > 0; $i--) {
                        /* ... */
                 }
          }

Or reference it directly in $GLOBALS:

          function eat_fruit($fruit) {
                 for ($i = $GLOBALS['chew_count']; $i > 0; $i--) {
                        /* ... */
                 }
          }

Discussion

If you use a number of global variables inside a function, the global keyword may make the syntax of the function easier to understand, especially if the global variables are interpolated in strings.

You can use the global keyword to bring multiple global variables into local scope by specifying the variables as a comma-separated list:

          global $age,$gender,shoe_size;

You can also specify the names of global variables using variable variables:

          $which_var = 'age';
          global $$which_var; // refers to the global variable $age

However, if you call unset() on a variable brought into local scope using the global keyword, the variable is unset only within the function. To unset the variable in the global scope, you must call unset() on the element of the $GLOBALS array:

          $food = 'pizza';
          $drink = 'beer';

          function party() {
                 global $food, $drink;

                 unset($food); // eat pizza
                 unset($GLOBALS['drink']); // drink beer
          }

          print "$food: $drink\n";
          party();
          print "$food: $drink\n";

This prints:

          pizza: beer
          pizza:

You can see that $food stayed the same, while $drink was unset. Declaring a variable global inside a function is similar to assigning a reference of the global variable to the local one:

          $food = $GLOBALS['food'];


No comments:

Post a Comment

Post Top Ad