phpglobal-variablesglobal

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?


Solution

  • 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);