How to declare a global variable in php?

PhpGlobal VariablesGlobal

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.

define("myconstant", "value"); 

class globalVars {

    static $a = false;

    static $b = 0;

    static $c = array('first' => 2, 'second' => 5);

}


function test($num) {

    if (!globalVars::$a) {

        $returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';

        globalVars::$a = true;

    } else {
        
        $returnVal = 'I forgot';

    }

    return $returnVal;

}

echo test(9); ---> The value of 9 + 0 + 5 is 14.

echo "<br>";

echo globalVars::$a; ----> 1

The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.

Solution 6 - Php

You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

$foo = "New";
$closure = (function($bar) use ($foo) {
	echo "$foo $bar";
})("York");

demo | info

Solution 7 - Php

You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.

Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.

Solution 8 - Php

You can declare global variables as static attributes:

class global {
    static $foo = "bar";
}

And you can use and modify it every where you like, like:

function echoFoo() {
    echo global::$foo;
}

Solution 9 - Php

What if you make use of procedural function instead of variable and call them any where as you.

I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.

function host()
{
   return "localhost";
}

Solution 10 - Php

$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:

function capital() {
	return my_var() . ' is the capital of Italy';
}

function my_var() {
	return 'Rome';
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLIGHTView Question on Stackoverflow
Solution 1 - PhpMrCodeView Answer on Stackoverflow
Solution 2 - PhpDaleView Answer on Stackoverflow
Solution 3 - PhpSajidur RahmanView Answer on Stackoverflow
Solution 4 - PhpPankaj KhairnarView Answer on Stackoverflow
Solution 5 - PhpThe One and Only ChemistryBlobView Answer on Stackoverflow
Solution 6 - PhpThieliciousView Answer on Stackoverflow
Solution 7 - PhpRobbieView Answer on Stackoverflow
Solution 8 - PhpAmir FoView Answer on Stackoverflow
Solution 9 - PhpVeshraj JoshiView Answer on Stackoverflow
Solution 10 - PhpDario FerrerView Answer on Stackoverflow