如何在PHP中声明一个全局变量? [英] How to declare a global variable in php?

查看:92
本文介绍了如何在PHP中声明一个全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

 <? 
$ a =localhost;
函数体(){
global $ a;
echo $ a;
}

函数head(){
global $ a;
echo $ a;
}

函数footer(){
global $ a;
echo $ a;
}
?>

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

解决方案

一个href =http://php.net/manual/en/reserved.variables.globals.php> $ GLOBALS 数组可以代替:

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

function body(){

echo $ GLOBALS ['a'];

手册

lockquote

包含所有变量引用的关联数组目前在脚本的全局范围内定义。变量名是数组的键。







如果您有一组函数需要一些公共变量,具有属性的类可能是一个不错的选择,而不是全局的:

  class MyTest 
{
保护$ a;

public function __construct($ a)
{
$ this-> a = $ a;
}

公共函数头()
{
echo $ this-> a;


public function footer()
{
echo $ this-> a;
}
}

$ a ='localhost';
$ obj = new MyTest($ a);


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?

解决方案

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

这篇关于如何在PHP中声明一个全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆