Accessing a global array inside class

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Guest
I have a very large global array which is defined in another file named "config.php".
I'm aiming to access this array like in the code below:

Code:
require_once('config.php');

echo("<br/>Outside of the class:<br/>");
echo('$CONFIG["DATABASE"]["USERNAME"] = ' . $CONFIG["DATABASE"]["USERNAME"] . "<br/>");
echo('$CONFIG["DATABASE"]["PASSWORD"] = ' . $CONFIG["DATABASE"]["PASSWORD"] . "<br/>");
echo('$CONFIG["DATABASE"]["HOSTNAME"] = ' . $CONFIG["DATABASE"]["HOSTNAME"] . "<br/>");
echo('$CONFIG["DATABASE"]["DATABASE"] = ' . $CONFIG["DATABASE"]["DATABASE"] . "<br/><br/>");

class Database
{
	// ...
	
	public function __construct()
	{
		// ...
		global $CONFIG;
		echo("Inside of the class constructor:<br/>");
		echo('$CONFIG["DATABASE"]["USERNAME"] = ' . $CONFIG["DATABASE"]["USERNAME"] . "<br/>");
		echo('$CONFIG["DATABASE"]["PASSWORD"] = ' . $CONFIG["DATABASE"]["PASSWORD"] . "<br/>");
		echo('$CONFIG["DATABASE"]["HOSTNAME"] = ' . $CONFIG["DATABASE"]["HOSTNAME"] . "<br/>");
		echo('$CONFIG["DATABASE"]["DATABASE"] = ' . $CONFIG["DATABASE"]["DATABASE"] . "<br/><br/>");
		// ...
	}
	
	// ...
	
	public function Connect()
	{
		// ...
		global $CONFIG;
		echo("Inside of a member function:<br/>");
		echo('$CONFIG["DATABASE"]["USERNAME"] = ' . $CONFIG["DATABASE"]["USERNAME"] . "<br/>");
		echo('$CONFIG["DATABASE"]["PASSWORD"] = ' . $CONFIG["DATABASE"]["PASSWORD"] . "<br/>");
		echo('$CONFIG["DATABASE"]["HOSTNAME"] = ' . $CONFIG["DATABASE"]["HOSTNAME"] . "<br/>");
		echo('$CONFIG["DATABASE"]["DATABASE"] = ' . $CONFIG["DATABASE"]["DATABASE"] . "<br/><br/>");
		// ...
	}
	
	// ...
};

Unfortunately, I can't access the array inside the class.
The output of my code is as below:

Outside of the class:
$CONFIG["DATABASE"]["USERNAME"] = root
$CONFIG["DATABASE"]["PASSWORD"] = pass
$CONFIG["DATABASE"]["HOSTNAME"] = 127.0.0.1
$CONFIG["DATABASE"]["DATABASE"] = my_db

Inside of the class constructor:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

Inside of a member function:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

What is wrong with my code?
Why doesn't it work?

Pleae help me, any help will be appreciated.
 
Accessing a global variable inside a class should not be a problem - Here is an example:
PHP:
$a = "Hello World";

function test() {
    $b = $GLOBALS['a'];
    echo "\n in function test(), a = $b";
}

class test1 {

    public function __construct() {
        $c = $GLOBALS['a'];
        echo "\n in class constructor, a = $c";
    }

    public function test2() {
        $c = $GLOBALS['a'];
        echo "\n in class, a = $c";
    }
}

echo "\n in global scope, a = $a";
test();

$obj1 = new test1();
$obj1->test2();
 
 
please post the code for the class instantiation as well as the call to the class member function.
 
My overall code is as below:

database.php
Code:
<?php
	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php');
	
	echo("<br/>Outside of the class:<br/>");
	echo('$CONFIG["DATABASE"]["USERNAME"] = ' . $CONFIG["DATABASE"]["USERNAME"] . "<br/>");
	echo('$CONFIG["DATABASE"]["PASSWORD"] = ' . $CONFIG["DATABASE"]["PASSWORD"] . "<br/>");
	echo('$CONFIG["DATABASE"]["HOSTNAME"] = ' . $CONFIG["DATABASE"]["HOSTNAME"] . "<br/>");
	echo('$CONFIG["DATABASE"]["DATABASE"] = ' . $CONFIG["DATABASE"]["DATABASE"] . "<br/><br/>");
	
	class Database
	{
		protected	$m_Link;
		private	$m_User;
		private	$m_Pass;
		private	$m_Host;
		private	$m_Data;
		private	$m_bConnected;
		
		public function __construct()
		{
			global $CONFIG;
			$this->m_User = $CONFIG["DATABASE"]["USERNAME"];
			$this->m_Pass = $CONFIG["DATABASE"]["PASSWORD"];
			$this->m_Host = $CONFIG["DATABASE"]["HOSTNAME"];
			$this->m_Data = $CONFIG["DATABASE"]["DATABASE"];
			$this->m_bConnected = false;
			echo("Inside of the class constructor:<br/>");
			$mCONFIG = $GLOBALS['CONFIG'];		// DIDN'T WORK THIS WAY EITHER!!
			echo('$CONFIG["DATABASE"]["USERNAME"] = ' . $mCONFIG["DATABASE"]["USERNAME"] . "<br/>");
			echo('$CONFIG["DATABASE"]["PASSWORD"] = ' . $mCONFIG["DATABASE"]["PASSWORD"] . "<br/>");
			echo('$CONFIG["DATABASE"]["HOSTNAME"] = ' . $mCONFIG["DATABASE"]["HOSTNAME"] . "<br/>");
			echo('$CONFIG["DATABASE"]["DATABASE"] = ' . $mCONFIG["DATABASE"]["DATABASE"] . "<br/><br/>");
			$this->Connect();
		}
		
		public function __destruct()
		{
			$this->Disconnect();
		}
		
		public function Connect()
		{
			global $CONFIG;
			echo("Inside of a member function:<br/>");
			echo('$CONFIG["DATABASE"]["USERNAME"] = ' . $CONFIG["DATABASE"]["USERNAME"] . "<br/>");
			echo('$CONFIG["DATABASE"]["PASSWORD"] = ' . $CONFIG["DATABASE"]["PASSWORD"] . "<br/>");
			echo('$CONFIG["DATABASE"]["HOSTNAME"] = ' . $CONFIG["DATABASE"]["HOSTNAME"] . "<br/>");
			echo('$CONFIG["DATABASE"]["DATABASE"] = ' . $CONFIG["DATABASE"]["DATABASE"] . "<br/><br/>");
			if ($this->IsConnected()) return true;
			$this->m_Link = mysql_connect($this->m_Host, $this->m_User, $this->m_Pass);
			if (!$this->m_Link)
			{
				$this->m_bConnected = false;
				return false;
			}
			if (!mysql_select_db($this->m_Data, $this->m_Link))
			{
				$this->Disconnect();
				return false;
			}
			return $this->m_bConnected = true;
		}
		
		public function Disconnect()
		{
			if ($this->IsConnected())
			{
				@$ret = mysql_close($this->m_Link);
				$this->m_bConnected = false;
				return $ret;
			}
			return true;
		}
		
		public function IsConnected()
		{
			return $this->m_bConnected;
		}
	};
	
	class YoutubeLinkDatabase extends Database
	{
		public function __construct()
		{
			parent::__construct();
		}
		
		public function __destruct()
		{
			parent::__destruct();
		}
		
		public function CloseDatabaseConnection()
		{
			$this->Disconnect();
		}
		
		public function DisplayRandomVideo()
		{
			$VideoId = $this->GetAVideoId();
			if ($VideoId == false) return false;
			print("<iframe src=\"http://www.youtube.com/watch?v=" . $VideoId . "\" width=\"0\" height=\"0\" frameborder=\"0\"></iframe>");
			$this->IncreaseWatchCount($VideoId);
		}
		
		private function GetAVideoId()
		{
			$Result = mysql_query("SELECT link FROM youtube_links;", $this->m_Link);
			if (!$Result) return false;
			$NumRows = mysql_num_rows($Result);
			if ($NumRows == 0) return false;
			$VideoLinks = array();
			for ($i=0; $i<$NumRows; $i++)
			{
				$row = mysql_fetch_array($Result, MYSQL_NUM);
				$VideoLinks[$i] = $row[0];
			}
			return $VideoLinks[array_rand($VideoLinks, 1)];
		}
		
		private function IncreaseWatchCount($VideoId)
		{
			mysql_query("UPDATE youtube_links SET visits=visits+1 WHERE link=\"" . $VideoId . "\""
						, $this->m_Link);
		}
	};
?>

config.php
Code:
<?php
	
	// The value of this constant specifies whether the code will run in the remote server
	// or will run in the local server.
	define("REMOTE_SERVER", false);
	
	// Database settings
	$CONFIG["DATABASE"] = array();
	if (REMOTE_SERVER)
	{
		$CONFIG["DATABASE"]["USERNAME"]	= "***";
		$CONFIG["DATABASE"]["PASSWORD"]	= "***";
		$CONFIG["DATABASE"]["HOSTNAME"]	= "***";
		$CONFIG["DATABASE"]["DATABASE"]	= "***";
	}
	else
	{
		$CONFIG["DATABASE"]["USERNAME"]	= "root";
		$CONFIG["DATABASE"]["PASSWORD"]	= "pass";
		$CONFIG["DATABASE"]["HOSTNAME"]	= "127.0.0.1";
		$CONFIG["DATABASE"]["DATABASE"]	= "my_db";
	}
	
	// ...
?>

overall_footer.html (I'm running this code in the template footer of my phpBB forum.)
Code:
	require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..\\..\\include\\database.php');
	$yld = new YoutubeLinkDatabase();
	$yld->DisplayRandomVideo();

Relative file locations:
site_root/include/database.php
site_root/include/config.php
site_root/forum/cache/overall_footer.html
 
This is what I get when I run your code:
Code:
Outside of the class:
$CONFIG["DATABASE"]["USERNAME"] = root
$CONFIG["DATABASE"]["PASSWORD"] = pass
$CONFIG["DATABASE"]["HOSTNAME"] = 127.0.0.1
$CONFIG["DATABASE"]["DATABASE"] = my_db

Inside of the class constructor:
$CONFIG["DATABASE"]["USERNAME"] = root
$CONFIG["DATABASE"]["PASSWORD"] = pass
$CONFIG["DATABASE"]["HOSTNAME"] = 127.0.0.1
$CONFIG["DATABASE"]["DATABASE"] = my_db

Inside of a member function:
$CONFIG["DATABASE"]["USERNAME"] = root
$CONFIG["DATABASE"]["PASSWORD"] = pass
$CONFIG["DATABASE"]["HOSTNAME"] = 127.0.0.1
$CONFIG["DATABASE"]["DATABASE"] = my_db

I did not use your directory structure. This looks like you are having trouble with the require_once.
 
Your code should work if you change this line
PHP:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..\\..\\include\\database.php');
 
to
PHP:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'include\\database.php');
 

You don't have to use directory separator and then a '\\'
 
johnj said:
Your code should work if you change this line
PHP:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..\\..\\include\\database.php');
 
to
PHP:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'include\\database.php');
 

You don't have to use directory separator and then a '\\'
It gave the following error when I did what you said:
Fatal error: require_once() [function.require]: Failed opening required '<site_root>\forum\includes\include\database.php'

Indeed, there is no such directory as "<site_root>\forum\includes\include".
 
I used your code,
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..\\..\\include\\database.php');
and it is working. I don't know why this is not working for you.

if I display the included path, this is what I see:
in database.php, include config, path=<siteroot>\include\config.php
in footer, include database.php,path=<siteroot>\forum\cache\..\..\include\database.php

In your original code can you display and post the path that you are using?
 
try this:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..'.DIRECTORY_SEPARATOR.'..\\include\\database.php');
 
johnj said:
try this:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..'.DIRECTORY_SEPARATOR.'..\\include\\database.php');
Now there is no error given. But still I can't access the elements of $CONFIG inside the class. I can access them outside the class. Once again the situation is very same to what I explain in my first post.

:help: :help: :help:
 
do a print_r($config) inside the constructor and tell me what it shows.
 
johnj said:
do a print_r($config) inside the constructor and tell me what it shows.

Code:
echo('***** <Code position written here> *****<br/>');
print_r($CONFIG); echo("<br/>");
echo('***********************************<br/><br/>');

Outputs
***** Outside the class *****
Array ( [DATABASE] => Array ( [USERNAME] => root [PASSWORD] => pass [HOSTNAME] => 127.0.0.1 [DATABASE] => my_db ) )
*****************************

***** Inside the constructor *****
**********************************

***** Inside a member function *****
************************************
 
what version of php are you using? what is your OS and webserver?
 
Try this:
In database.php right below this line,
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php'); add another line which says global $CONFIG; it should look like this:
PHP:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php'); 
global $CONFIG; 
 

You should have global $CONFIG at two places (outside the class and inside the class). Test it.
 
johnj said:
what version of php are you using? what is your OS and webserver?
PHP Version: 5.3.0
OS: Windows 7 x64 Ultimate SP1
WEB Server: Apache 2.2
(I'm using Xampp.)

johnj said:
Try this:
In database.php right below this line,
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php'); add another line which says global $CONFIG; it should look like this:
PHP:
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php'); 
global $CONFIG; 
 

You should have global $CONFIG at two places (outside the class and inside the class). test it.

Output without any "global $CONFIG;" after "require_once()":
Outside of the class:
$CONFIG["DATABASE"]["USERNAME"] = root
$CONFIG["DATABASE"]["PASSWORD"] = pass
$CONFIG["DATABASE"]["HOSTNAME"] = 127.0.0.1
$CONFIG["DATABASE"]["DATABASE"] = my_db

***** Outside the class *****
Array ( [DATABASE] => Array ( [USERNAME] => root [PASSWORD] => pass [HOSTNAME] => 127.0.0.1 [DATABASE] => my_db ) )
*****************************

Inside of the class constructor:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

***** Inside the constructor *****

**********************************

Inside of a member function:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

***** Inside a member function *****

************************************

Output with a "global $CONFIG;" after "require_once()":
Outside of the class:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

***** Outside the class *****

*****************************

Inside of the class constructor:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

***** Inside the constructor *****

**********************************

Inside of a member function:
$CONFIG["DATABASE"]["USERNAME"] =
$CONFIG["DATABASE"]["PASSWORD"] =
$CONFIG["DATABASE"]["HOSTNAME"] =
$CONFIG["DATABASE"]["DATABASE"] =

***** Inside a member function *****

************************************

:( :help: :help: :help: :(
 
The global array is getting unset or corrupted somewhere.

There is an example which starts like this,$a = "Hello World"; this is in my second post. Can you test that example and tell me if 'global' is working in that example.

Is this the only three files (database,config and footer) that is involved OR do you have more files when you run?
 
johnj said:
The global array is getting unset or corrupted somewhere.
Yeah, seem to me like that also. Starting to define the class somehow deletes the global variables. Can it be because of a PHP.ini setting, or can it be because of that phpBB forum de-registers the globals? If so, what should I do?

johnj said:
There is an example which starts like this,$a = "Hello World"; this is in my second post. Can you test that example and tell me if 'global' is working in that example.
Your example code:
Code:
    echo("///////////////////////////////////////////////////////<br/>");
    $a = "Hello World";

    function test() {
        $b = $GLOBALS['a'];
        echo "\n in function test(), a = $b<br/>";
    }

    class test1 {

        public function __construct() {
            $c = $GLOBALS['a'];
            echo "\n in class constructor, a = $c<br/>";
        }

        public function test2() {
            $c = $GLOBALS['a'];
            echo "\n in class, a = $c<br/>";
        }
    }

    echo "\n in global scope, a = $a<br/>";
    test();

    $obj1 = new test1();
    $obj1->test2();
    echo("///////////////////////////////////////////////////////<br/><br/>");
And its output:
///////////////////////////////////////////////////////
in global scope, a = Hello World
in function test(), a =
in class constructor, a =
in class, a =
///////////////////////////////////////////////////////

johnj said:
Is this the only three files (database,config and footer) that is involved OR do you have more files when you run?
The forum itself is an enormous mass of code running. But besides that, I only involved the two files (config.php and database.php) I mentioned, there is nothing else.
 
......because of that phpBB forum de-registers the globals....................................The forum itself is an enormous mass of code running. But besides that, I only involved the two files (config.php and database.php) I mentioned, there is nothing else.

I think the code for phpBB is the culprit.

Things you can check:
a).You need to check if there is another variable named $CONFIG somewhere , is it getting set and unset ?
b).Are they unsetting $GLOABLS super global array some where?

It is difficult to debug such a huge mass of code through a forum - sorry!
 
You should take these 3 files outside your forum code and run it alone. Then, if it works, you know that phpBB is influencing your output.
 
Back
Top