WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know this works.
In functions.php do:

$variable = "value";

and in header.php use:

global $variable;
echo $variable;

Is it possible to set a global variable in template page or include php file?

share|improve this question
Thanks @ialocin – Jows Jun 4 '14 at 11:00
My pleasure, take a look at help: formatting to learn more about that. – ialocin Jun 4 '14 at 12:25
up vote 4 down vote accepted

Anywhere in your script, you can define a global variable as follow:

Using the superglobal $GLOBALS array. This array is predefined by PHP, and is available in all scopes.

It's an associate array, containing all global variables as a key-value pair. ie: the key will be the variable name, and value will be the value of the variable.

$GLOBALS['variablename'] = 'variablevalue';

And it can be accessed as:

$variable = $GLOBALS['variablename'];


global $variable;

to know more ref: PHP Variable Scope

EDIT: While answering i assumed the user knew about method 2, but on rereading it seems maybe he is not aware of it, so am mentioning it below.

Method 2:

you can define global variable using the 'global' keyword as well. eg code:


class testScope()
   function setMsg($msg = 'Hi')
    //the variable need not be already defined in the global scope. 
   global $say;
   $say = 'Hi';

  function say()
    global $say;
    echo $say;


function getFile1()


$sayer = new testScope();

$sayer->setMsg(); // this will create a new global variable. 
global $say; 
echo $say; 

$say = "I changed it in global scope";

$sayer->say(); // 'I changed it in global scope'

$sayer->set('i changed it inside class');
echo $say; // ' i changed it inside class'

Note: The code is untested

share|improve this answer
Yeah. It works. Thanks @MortalViews. – Jows Jun 4 '14 at 11:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.