Global

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Global

Post by evilmonkey »

Hello. This sounds really n00bish, and with my number of posts, I must apologize ahead of time for asking this.

My question is now about the "global" command (command?) in PHP. I saw this used:

Code: Select all

global $var
$var="Hello";
From what I understand, this defines a global variable. How can it be called upon in later scripts? I know in sessions, you can call upon $_SESSION array elemnts if you have session_start(); at the top of your page. In the case of global $var, I don't see how this happens. Can some one please tell me? Thanks.

Cheers!

P.S. I'm asking this because I couldn't find it in the PHP manual. Perhaps I just didn't look hard enough ;)
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

It's used in functions().

PHP functions() can't see variables set outside of them unless to 'show' them.... for example...

Code: Select all

<?php

function changebob()
{
global $name;
$name = "i am not bob";
}

$name = "bob";
changebob();
echo($name);


?>
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Post by evilmonkey »

Ah, I see now. So a variable must be set as a global to be used outside the function where it's defined.

Thanks.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

nearly.... a variable must called called using the global command inside of a function if you want to use that variable inside the function.... unless you send the variable directly to the function.

Let's say a form as just been submitted to a php page and in the form you have $name and $email. If you have a function which checks if the email address is valid there are two ways to send the $email variable to that function....

Code: Select all

<?php

function checkemail($var)
{
// check if $var is valid

return true // or false depending on result
}

$is_email_valid = checkemail($email);

?>

Code: Select all

<?php

function checkemail()
{
global $email
// check if $email is valid

return true // or false depending on result
}


$is_email_valid = checkemail();

?>

.... hope that helps :)
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Post by evilmonkey »

Yup, sure does :)

Thanks.
Post Reply