Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 at 11:00
    
My pleasure, take a look at help: formatting to learn more about that. –  ialocin Jun 4 at 12:25

1 Answer 1

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'];

or

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:

//file1.php

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;
  } 
}

//file2.php 

function getFile1()
{
  include('file1.php');
}

getFile1();

$sayer = new testScope();

$sayer->setMsg(); // this will create a new global variable. 
$sayer->say();
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 at 11:01

Your Answer

 
discard

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.