200

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?

LIGHT
  • 5,604
  • 10
  • 35
  • 78

10 Answers10

292

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);
MrCode
  • 63,975
  • 10
  • 90
  • 112
89

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;
}
Dale
  • 10,384
  • 21
  • 34
  • 2
    What happens when `FOOTER_CONTENT` is attempted to modify? Is it just like `final` in Java or `const` in C, C++ and C#? – Lion Nov 23 '12 at 14:05
  • 5
    If you try to define FOOTER_CONTENT a second time, php will throw a notice about it – Dale Nov 23 '12 at 14:06
  • I needed to calculate the current unix epoch time each time a page is loaded, then use that value in a couple calculations (functions). "define" worked for me. Initially, I didn't see that "echo FOOTER_CONTENT;" didn't have a preceding '$' and I got errors. – user208145 Jun 07 '16 at 02:28
  • 2
    If variable is not going to change its not a variable. Isn't it?! – Sajidur Rahman Mar 28 '18 at 17:11
  • Maybe in 2012, this was an acceptable answer, but using a `define()` for the content of the footer is not a good practice in today's php. – istepaniuk Jan 21 '21 at 18:05
  • @istepaniuk Feel free to edit, I don't keep track of all my answers, especially when they're from 8 years ago. – Dale Jan 25 '21 at 16:51
  • Upvoted, thanks! To be clear, [this does work on classes, too](https://ideone.com/VQZjAj). And whoa, that's actually the constant I was going to define! – HoldOffHunger Nov 08 '21 at 22:46
45

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.

Sajidur Rahman
  • 2,764
  • 1
  • 27
  • 26
  • 1
    What if you use `function name() { global $variable; }` but the `$variable` has not been declared outside of the function? Is a "global" variable created by PHP? And can it be used from other functions later on? – Avatar Oct 12 '22 at 06:35
  • Try it. It won't take more than 5 minutes. ;) – Sajidur Rahman Feb 27 '23 at 16:49
  • $_GLOBALS cannot be changed in user space anymore (As of PHP 8.1.0, write access to the entire $GLOBALS array is no longer supported ) – theking2 Mar 07 '23 at 14:23
34

Add your variables in $GLOBALS super global array like

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

and use it globally as

echo $GLOBALS['variable']

or you can use constant which are accessible throughout the script

define('HOSTNAME', 'localhost');  

usage for define (NOTE - without the dollar)

echo HOSTNAME;
Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
Pankaj Khairnar
  • 3,028
  • 3
  • 25
  • 34
10

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.

  • This is a good solution for many reasons. Class static requires just a few characters added to the basic variable name: G::$Name, where the declaration looks like this: class G { static $Name, $Name2;} Note that G can be truly global variables, then E could be used for variables relating to Employees. This is easier to program with than the full-scale object-oriented paradigm supported by PHP. If constants are truly needed, you can declare them after "const" just like the variables declared after "static"--just leave out the dollar signs. G::Example would be an example of a global constant. – David Spector Nov 22 '18 at 01:26
9

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

Thielicious
  • 4,122
  • 2
  • 25
  • 35
7

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;
}
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
5

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.

Robbie
  • 17,605
  • 4
  • 35
  • 72
0

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";
}
Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45
-3

$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';
}
Dario Ferrer
  • 804
  • 1
  • 8
  • 22
  • 1
    Here the function is not A global variable. – Pratik Soni Jul 21 '20 at 15:25
  • @PratikSoni I never said it was a global variable. Next time read better, that way you won't spread negative ratings everywhere. – Dario Ferrer Jul 22 '20 at 19:15
  • I am sorry if you think this ie misleading. But i was going in context of actual question. And the answer is not even little bit near by to the question. "How to declare a global variable in php?" – Pratik Soni Jul 24 '20 at 14:26