Use of global variables within plugin [closed]

There’re easier ways than this. As @Wyck already stated that using globals is bad idea, here’s a short explanation and how to:

Why globals are bad:

1) Everyone can access them everywhere. First this sounds nice, but you can as well do the following:

// Your code: default value
global $foo;
$foo = 'bar';

// User setting:
global $foo;
$foo = get_option( 'baz' );

// Later in your code
if ( 'bar' === $foo )
    // do something important

// Now I, the end user, do this in a template
// or Ernie, the novice developer, does this in his 3rd party plugin:
$GLOBALS['foo'] = 42;

and suddenly nothing works like expected. Simple as it is: Globals can get intercepted. They aren’t conflict free and no one can ever be sure what they contain.

2) After you now know that they can change on the fly, you know that they’re unpredictable. And if you want to trace them back with your IDE (for e.g. PHPStorm, Eclipse/Aptana, etc.) then you’ll never find out where their origin is or where exactly they get changed… unless you sit down for quite a while and use things like Breakpoints and something like XDebug and know your way around.

3) Do I really have to write more? I guess not.

Conclusion: As most options are autoloaded, they’re already present on each page/request and don’t need to be wrapped in a global. Simply call get_option() whenever you need it.

How to move Data from PHP to JS

Simple as it is: wp_localize_script()

Example: (can be used with login_enqueue_scripts and admin_enqueue_scripts hooks as well)

add_action( 'wp_enqueue_scripts', 'wpse115840_scripts' );
function wpse115840_scripts()
{
    wp_enqueue_script( 'wpse_handle', etc... );
    // Here goes the magic:
    wp_localize_script( 'wpse_handle', 'wspeObject', array(
        'foo' => 'bar',
        'bar' => get_option( 'baz' )
    ) );
}

Now you can access all the data from the wp_localize_script() array (the 3rd arg) in your javascript file that you just registered/enqueued simply by calling wpseObject. The following example would now give you the value bar:

console.log( wpseObject.foo );

and your wpseObject.bar would hold your baz setting value.