[php] 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?

This question is related to php global-variables global

The answer is


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.


Let's think a little different, You can use static parameters:

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

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

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

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

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.


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

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

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

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.


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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to global-variables

What is the best way to declare global variable in Vue.js? How do I turn off the mysql password validation? How to declare Global Variables in Excel VBA to be visible across the Workbook How to create a global variable? global variable for all controller and views How to define global variable in Google Apps Script How to modify a global variable within a function in bash? Using a global variable with a thread Is it possible to use global variables in Rust? How to access global js variable in AngularJS directive

Examples related to global

How to access global variables Passing Variable through JavaScript from one html page to another page Change Button color onClick Can I make a function available in every controller in angular? How to declare a global variable in php? PHP pass variable to include Global Git ignore Passing a variable from one php include file to another: global vs. not Ruby on Rails: Where to define global constants? JavaScript: Global variables after Ajax requests