Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple question: global $blahblah

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi there. I have included "config.inc" which contains my database's name,username and password on the top of my page. I wonder why the script wouldn't work properly if I DON'T declare those three variables($dbname,$dbuser,$dbpass) as GLOBAL in every function that involved using database.(as shown below). Can't I write it JUST FOR ONCE in my script? What is the scope of GLOBAL and what is the main purpose of declaring it? Please forgive my inersia as I am still new to php. Helps are very appreciated. Thank you.

//config.inc
<?
$dbname=&quot;foobar&quot;;
$dbuser=&quot;foobar&quot;;
$dbpass=&quot;foobar&quot;;
?>

//testpage.php
<?
include('config.inc');

function use_db_1() {
global $dbname,$dbuser,$dbpass;
..
..
}

function use_db_2() {
global $dbname,$dbuser,$dbpass;
..
..
}

function use_db_3() {
global $dbname,$dbuser,$dbpass;
..
..
}

?>








 
That's not a good way of programing, but well is a way.

See this:

Inside the function you should refer them as $GLOBALS[varname] instead of $varname.

PHP is very different from other languages, regarding the variables scopes. Inside a function, if you don't refer that the var is the global one, it assumes it's local. Anikin
Hugo Alexandre Dias
Web-Programmer
anikin_jedi@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top