php 如何在php中声明一个全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13530465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:37:39  来源:igfitidea点击:

How to declare a global variable in php?

phpglobal-variablesglobal

提问by LIGHT

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 $aaccessible in all the functions at once? without making use of global $a;more?

有什么方法可以在一个地方定义全局变量并使变量$a可以在所有函数中同时访问?不使用global $a;更多?

回答by MrCode

The $GLOBALSarray can be used instead:

$GLOBALS阵列可以用来代替:

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

回答by Dale

If the variable is not going to change you could use define

如果变量不会改变,你可以使用 define

Example:

例子:

define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');

function footer()
{
    echo FOOTER_CONTENT;
}

回答by Pankaj Khairnar

Add your variables in $GLOBALS super global array like

在 $GLOBALS 超级全局数组中添加您的变量,例如

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

and use it globally

并在全球范围内使用它

or you can use constant which are accessible throughout the script

或者您可以使用在整个脚本中都可以访问的常量

define('HOSTNAME', 'localhost');  

回答by Sajidur Rahman

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 globalkeyword:

如果变量在函数之外声明,则它已经在全局范围内。所以不需要申报。但是从哪里调用这个变量必须有权访问这个变量。如果您从函数内部调用,则必须使用global关键字:

$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.

在函数外使用 global 关键字不是错误。如果你想在函数中包含这个文件,你可以将变量声明为global.

config.php

global $variable;

$variable = 5;


other.php

function name()
{
    require_once __DIR__ . '/config.php';
}

You can use $GLOBALSas well. It's a superglobal so it has access everywhere.

您也可以使用$GLOBALS。它是一个超全局的,所以它可以在任何地方访问。

$GLOBALS['variable'] = 5;

function name()
{
    echo $GLOBALS['variable'];
}

Depending on your choice you can choose either.

根据您的选择,您可以选择两者之一。

回答by The One and Only ChemistryBlob

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 statickeywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.

static关键字必须存在于其他的类瓦尔$ A,$ b和$ C不会被全局范围。

回答by Thielicious

You can try the keyword usein Closurefunctions or Lambdasif this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

如果这符合您的意图,您可以useClosure函数或Lambdas 中尝试关键字...不过是 PHP 7.0。不是那更好,而只是一种选择。

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

demo| info

演示| 信息

回答by Robbie

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.

或者,您可以使用类中的常量技巧,例如 class::constant。您还可以通过向类声明静态属性来使它们可变,如果您想更改静态属性,则可以使用函数来设置静态属性。

回答by Amir Fo

Let's think a little different:

让我们换个角度思考:

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

And you can use and modify it everyway you like, like:

您可以随心所欲地使用和修改它,例如:

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

回答by Dario Ferrer

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

$GLOBALS[]正确的解决方案,但由于我们谈论的是替代方案,因此函数也可以轻松完成这项工作:

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

function my_var() {
    return 'Rome';
}

回答by Veshraj Joshi

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.

我通常会收集配置值并将它们放入带有 return 语句的函数中。我只包括我需要使用全局值并调用特定函数的地方。

function host()
{
   return "localhost";
}