Global Variables in php/worpdress

Posted in Wordpress , Intermediate 29 Jun 2020

In this post, we will be discussing on global keyword used in wordpress and basic php concepts behind it. Before, we move further with details, it's important to understand the concept of scoping in php.

Concept of scoping in php:

PHP as a language uses function scoping. What this means is that any given unit of PHP will either have access to variables in the global scope, or only have access to the variables declared inside the currently executing function. And variables declared in a function are not going to be available globally unless they explicitly declare that they are.

$global = "I am a global variable because I wasn't defined inside a function.";

function my_global_function() {

    global $global;

    echo $global;

}

function my_nonglobal_function($global) {

    echo $global;

}

my_global_function();

my_nonglobal_function($global);

function make_something_else_global() {

   global $second_global;

   $second_global = "I'm global becuase the word global was used inside a function.";

}

make_something_else_global();

echo $second_global;

In the above snippet, $global is a global variable as it is not declared locally in any function

There are two approaches of accessing $global variable inside a function

  1. Use 'global' keyword as done in my_global_function
  2. Passing global variable as function argument as done in my_nonglobal_function function

A variable can be made global from inside the function as well and it is done as shown in make_something_else_global function.Having said the above, there are two uses of global keyword

  1. Accessing global variables inside a function
  2. Creating global variables inside a function

The post is inspired from https://wpshout.com/php-globals-variable-scope-wordpress/