How to declare a global variable in php?

I have code something like this:

<?
    $a="localhost";
    function body(){
        global $a;
        echo $a;
    }

    function head(){
        global $a;
        echo $a;
    }

    function footer(){
        global $a;
        echo $a;
    }
?>

is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?


The $GLOBALS array can be used instead:

$GLOBALS['a'] = 'localhost';

function body(){

    echo $GLOBALS['a'];
}

From the Manual:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.


If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:

class MyTest
{
    protected $a;

    public function __construct($a)
    {
        $this->a = $a;
    }

    public function head()
    {
        echo $this->a;
    }

    public function footer()
    {
        echo $this->a;
    }
}

$a = 'localhost';
$obj = new MyTest($a);

If the variable is not going to change you could use define

Example:

define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');

function footer()
{
    echo FOOTER_CONTENT;
}

If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:

$variable = 5;

function name()
{
    global $variable;
    
    $value = $variable + 5;
    
    return $value;  
 
}

Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.

// config.php

global $variable;

$variable = 5;

// other.php

function name()
{
    require_once __DIR__ . '/config.php';
}

You can use $GLOBALS as well. It's a superglobal so it has access everywhere.

$GLOBALS['variable'] = 5;

function name()
{
    echo $GLOBALS['variable'];
}

Depending on your choice you can choose either.


Add your variables in $GLOBALS super global array like

$GLOBALS['variable'] = 'localhost'; 

and use it globally

or you can use constant which are accessible throughout the script

define('HOSTNAME', 'localhost');