Reputation: 259
I have this code:
<?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;
}
}
?>
And I get the error:
Use of undefined constant
I'm not sure why this error is occurring. Perhaps I am declaring global variables wrong. What's going on here?
Upvotes: 0
Views: 826
Reputation: 1364
The $GLOBALS array can be used instead:
$GLOBALS['db_initiallized'] = false;
$GLOBALS['db_connection'] = NULL;
function db_init(){
echo $GLOBALS['db_initiallized'];
echo $GLOBALS['db_connection'];
}
OR
If the variable is not going to change you could use define.
define('db_initiallized', FALSE);
define('db_connection', NULL);
function db_init()
{
echo db_initiallized;
echo db_connection;
}
OR
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: 1