LIGHT
LIGHT

Reputation: 5712

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?

Upvotes: 206

Views: 528103

Answers (10)

Sajidur Rahman
Sajidur Rahman

Reputation: 3060

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

NOTE: As of PHP 8.1.0, write access to the entire $GLOBALS array is no longer supported, which was an acceptable solution before PHP 8.1.0.

Upvotes: 47

Pankaj Khairnar
Pankaj Khairnar

Reputation: 3108

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;

Upvotes: 35

Amir Forsati
Amir Forsati

Reputation: 5960

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

Upvotes: 8

Dario Ferrer
Dario Ferrer

Reputation: 826

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

Upvotes: -2

Veshraj Joshi
Veshraj Joshi

Reputation: 3579

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

Upvotes: 1

Thielicious
Thielicious

Reputation: 4442

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

Upvotes: 9

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.

Upvotes: 10

MrCode
MrCode

Reputation: 64526

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

Upvotes: 296

Dale
Dale

Reputation: 10469

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

Upvotes: 91

Robbie
Robbie

Reputation: 17710

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.

Upvotes: 5

Related Questions