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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

global variable issue

Status
Not open for further replies.

skiflyer

Programmer
Sep 24, 2002
2,213
US
I know I know how to do this, but I'm having a total blankout...

I want to set a variable in my main script which will get called all over the place in other scripts it launches and inside functions.... what is it I do to make it global? (I don't really want to use session variables)

-Rob
 
So I can't do this?

Controller.php
===================
<?
$test = true;
if ($test) {
$db = &quot;test.mdb&quot;;
} else {
$db = &quot;real.mdb&quot;;
}

include &quot;script2.php&quot;
?>
====================

script2.php
====================
<?
lotsa code

include &quot;connect.php&quot;;

db manipulation code
?>
====================

connect.php
====================
<?
connection code which somehow manipulates $db
?>
====================
 
Well, apparently not... but there's a definite hack... for anyone who's interested... in the first script just put

function test() {
$test = 1;
if ($test) {
return &quot;something&quot;;
} else {
return &quot;something else&quot;;
}
}

 
That is a single invocation of a script. It's just that the invoked script includes other script files. But it's a single invocation.

If the data is static (like the login credentials to a database server), you can use PHP's define() function to define constants. Define all your constants in a separate file and include it. You can also use PHP's parse_ini_file() function to read them from a file.

If the data is static, you can make it global pretty easily. If the data comes from an HTML form, $_POST and $_GET are already superglobal -- just reference the data. (I recommend using those variables in any regard -- it improves code maintainability)

If the data is being generated by some other part of a PHP script, stuff the value into $GLOBALS as one of its array elements. Then you can reference the data anywhere.

If you have a single datum which multiple user-defined functions need to use, use the &quot;global&quot; operator. Want the best answers? Ask the best questions: TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top