Forum Moderators: coopster

Message Too Old, No Replies

global variable

         

yllai

4:45 am on Dec 16, 2006 (gmt 0)

10+ Year Member



Hi,

In my index.php, have if statement. default is check user password (function login()), if match, then will retrieve user id from DB.
if (!$_REQUEST['Submit']) {
login();
} elseif ($_REQUEST['Submit'] == "AAA") {
AAA();
}elseif ($_REQUEST['Submit'] == "BBB") {
BBB();
}

function AAA(){
//something here
}
function BBB(){
//something here
}

So, what I want to do is I want the 'id' to be use in every function (AAA, BBB)...I have tried to assign it as global variable at the beginning of page, then echo in function AAA(), but it not work. What is my mistake? Anyone can help? Anyway to do it? Where can I get this type of example or tutorial?

Thanks in advenced.

dreamcatcher

10:05 am on Dec 16, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi yllai,

Have you tried declaring it a global from within the function?

function AAA()
{
global $id;

echo $id;
}

Or you can pass the id into the function like this:

function AAA($id)
{
echo $id;
}

dc

mcibor

10:20 pm on Dec 16, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi yllai

if you did:

global $id;

function AAA()
{
echo $id;
}

then it will not work.
Use the suggestion by dreamcatcher. However I would recomend using the second option.

Why?


function AAA()
{
global $id;
$id++;
echo "ID+1 = $id<br />";
}
$id = 2;
AAA();
echo "Id = $id";

will output:
ID+1 = 3
Id = 3

However


function AAA($id)
{
$id++;
echo "ID+1 = $id<br />";
}
$id = 2;
AAA($id);
echo "Id = $id";

will output:
ID+1 = 3
Id = 2

Regards
Michal