使用全局定义的变量时遇到问题:'使用未定义的常量'

时间:2014-05-27 00:35:53

标签: php mysql database-connection

我有这段代码:

<?php

$db_initiallized = false;
$db_connection = NULL;

function db_init()
{
    global $db_initiallized, $db_connection;

    if(!$db_initiallized) //error occurs on this line
    {
        $db_connection = mysql_connect("server", "username", "password");
        if(!$db_connection)
        {
            echo 'Connection failure!';
            exit();
        }

        $db_initiallized = true;
    }
}

?>

我收到错误:

Use of undefined constant

我不确定为什么会出现这种错误。也许我宣称全局变量是错误的。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

可以使用$GLOBALS数组:

$GLOBALS['db_initiallized'] = false;
$GLOBALS['db_connection'] = NULL;

function db_init(){

    echo $GLOBALS['db_initiallized'];
    echo $GLOBALS['db_connection'];
}

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

define('db_initiallized', FALSE);
define('db_connection', NULL);

function db_init()
{
    echo db_initiallized;
    echo db_connection;
}

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

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