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