PDA

Click to See Complete Forum and Search --> : variables


Beasts
Nov 5th, 2007, 05:53 PM
i am pretty new to PHP and am having a little problem.
my code is like this.


function thing()
{
include("global_variables.php");
echo($variable1);
}

function thing2()
{
include("global_variables.php");
echo($variable2);
}


this is not how i want it to be. the question is, is it possible to include the global variables file just once to make it work with all the functions?

dclamp
Nov 5th, 2007, 08:37 PM
well there are no global variables. The best idea is to have a configuration file, or settings file where are the configs are made.

A config file might include MySQL connections, variables for site title, or other things. And on all the pages that you need the mysql connections, you would include the config file.

so for ex:

//CONFIG FILE:

$mysitetitle = "My Cool Site";


And my page:


<?php include("config.php"); ?>

<title><?php echo $mysitetitle; ?></title>
... html

penagate
Nov 5th, 2007, 09:00 PM
Dclamp, all variables initialised outside a function or class are global.
To use these within a function you must import them using the global keyword. Otherwise, you create a local variable of the same name, which is discarded once it goes out of scope.

$bar = 10;
echo $bar;

function foo()
{
global $bar;
echo ++$bar;
}

echo $bar;

dclamp
Nov 5th, 2007, 09:59 PM
So i can use $bar on another page without including it?

penagate
Nov 5th, 2007, 10:16 PM
No. What would give you that idea?

dclamp
Nov 6th, 2007, 12:02 AM
well then it is really not required to set the variables as global then... right?

penagate
Nov 6th, 2007, 12:07 AM
I don't understand your question. Look up variable scope in the online manual if you want a more thorough explanation and let's leave this thread for the thread starter.

visualAd
Nov 7th, 2007, 02:12 PM
I don't understand your question. Look up variable scope in the online manual if you want a more thorough explanation and let's leave this thread for the thread starter.
He has clearly read my last PHP post out of context ;)