Banner

Sponsor

Login


Welcome Back!
Guest
Guest

Register

Lost your password?

90 users online



Tutorials - Variable Scope, Variable Variables, Sessions

Tutorials - Variable Scope, Variable Variables, Sessions

Currently viewing this thread: 1 (0 members and 1 guests)


Page 1 out of 3
Phil

Phil

with Mr. Jones
Status: Offline!

Tutorials - Variable Scope, Variable Variables, Sessions

Just a few tutorials to help people, and to help make it so the same questions aren't asked over and over again.

[b]Variable Scope[/b]

In PHP, there are 4 scopes - normal, variable, global, and superglobal.

When you set a variable, it is automatically put in a certian scope. Think of scopes as the ends of a telescope - when looking through it, you can see some things, but not everything.

Say you set a variable in the middle of your script; ie:

[php]
# some code
$currentSong = 'Mest - Jaded.mp3';
print $currentSong;
# more code
[/php]

Variable $currentSong is set in the [i]normal[/i] scope. This means its generally accessable everywhere except inside functions and classes. For example, say you have a function that stores our $currentSong.

[php]
function storeCurrentSong() {
if(isset($currentSong)) {
mysql_query("insert into 'storedSongs' set song = $currentSong");
else {
print 'variable $currentSong is not set!';
}
}
[/php]

If you were to run this function (assuming database was connecting and table structure was made) it would tell you 'variable $currentSong is not set!'.

This is because functions have a different variable scope then the normal scope. Variables from outside the function (ie from the rest of the script) aren't accessable by default. Also, variables set in functions aren't accessable outside of the functions. That means if i do
[php]
<?php

function set() {
$v = 'set';
}

set();
print $v;
?>
[/php]

it will return [i]Notice: Undefined variable: v in e:\server\test.php on line 8[/i] because it isn't accessable by default. Also, variables set inside functions are NOT accessable by default inside other functions.

So, how do we solve this? We need to put the variable we need into the [i]global[/i] scope. Php has a construct called 'global' (hah - its simple!) that will do this for you. For example, we can add this line to our storeCurrentSong function to global our variable.

[php]
function storeCurrentSong() {
global $currentSong;
if(isset($currentSong)) {
mysql_query("insert into 'storedSongs' set song = $currentSong");
else {
print 'variable $currentSong is not set!';
}
}
[/php]

Thats it - we moved the variable into the global scope, which is the third php scope. A note about the global scope, as pointed out by Jerome:
[QUOTE][i]Originally posted by lasnaranjas [/i]
Just a little note Ares,

you run into problems modifying global variables (in some situations)

so its safer to use $GLOBALS['varname'] if you plan to modify the variable.


-Jerome [/QUOTE]


Finally, theres the [i]superglobal[/i] scope. PHP sets these automatically - you dont have to do anything. They are actually superglobal arrays that PHP sets. They can be used ANYWHERE in your script without any previous globaling.

These are the superglobal variables.

[quote][i]Quoted from PHP manual[/i]
$GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.

$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).

$_GET
Variables provided to the script via HTTP GET. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.

$_ENV
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST
Variables provided to the script via any user input mechanism, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().

Note: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

$_SESSION
Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.
[/quote]

Just a few notes - $_GET is from the query string (ie page.php?var=1) and $_POST is from forms with method set to post.

You should never have to use $_REQUEST - use alternatives let $_GET/POST/SESSION/COOKIE/ETC - its much better coding practice.

These are the variables in the $_SERVER superglobal array - your values for the vars may be different, this is from my machine.
[quote][i]Quoted from My PHP[/i]
Array
(
[COMSPEC] => C:\\WINDOWS\\COMMAND.COM
[DOCUMENT_ROOT] => e:/server
[HTTP_ACCEPT] => */*
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_ACCEPT_LANGUAGE] => en-us
[HTTP_CONNECTION] => Keep-Alive
[HTTP_COOKIE] => lastview=1055257218
[HTTP_HOST] => localhost
[HTTP_USER_AGENT] => Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)
[PATH] => C:\\WINDOWS;C:\\WINDOWS\\COMMAND
[REDIRECT_STATUS] => 200
[REDIRECT_URL] => /test.php
[REMOTE_ADDR] => 127.0.0.1
[REMOTE_PORT] => 1053
[SCRIPT_FILENAME] => d:/php/php.exe
[SERVER_ADDR] => 127.0.0.1
[SERVER_ADMIN] => [email]server@aesthetic-theory.com[/email]
[SERVER_NAME] => localhost
[SERVER_PORT] => 80
[SERVER_SIGNATURE] => <ADDRESS>Apache/1.3.27 Server at localhost Port 80</ADDRESS>

[SERVER_SOFTWARE] => Apache/1.3.27 (Win32)
[WINDIR] => C:\\WINDOWS
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /php/php.exe
[PATH_INFO] => /test.php
[PATH_TRANSLATED] => e:\\server\\test.php
[PHP_SELF] => /test.php
[argv] => Array
(
)

[argc] => 0
)
[/quote]

To access [INSERT_SOMETHING_HERE] you would do $_SERVER['INSERT_SOMETHING_HERE'] in your script.

These are the variables in the $_ENV superglobal array - your values for the vars may be different, this is from my machine.
[quote][i]Qoutoed From My PHP[/i]
Array
(
[COMSPEC] => C:\\WINDOWS\\COMMAND.COM
[DOCUMENT_ROOT] => e:/server
[HTTP_ACCEPT] => */*
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_ACCEPT_LANGUAGE] => en-us
[HTTP_CONNECTION] => Keep-Alive
[HTTP_COOKIE] => lastview=1055257218
[HTTP_HOST] => localhost
[HTTP_USER_AGENT] => Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)
[PATH] => C:\\WINDOWS;C:\\WINDOWS\\COMMAND
[REDIRECT_STATUS] => 200
[REDIRECT_URL] => /test.php
[REMOTE_ADDR] => 127.0.0.1
[REMOTE_PORT] => 1053
[SCRIPT_FILENAME] => d:/php/php.exe
[SERVER_ADDR] => 127.0.0.1
[SERVER_ADMIN] => [email]server@aesthetic-theory.com[/email]
[SERVER_NAME] => localhost
[SERVER_PORT] => 80
[SERVER_SIGNATURE] => <ADDRESS>Apache/1.3.27 Server at localhost Port 80</ADDRESS>

[SERVER_SOFTWARE] => Apache/1.3.27 (Win32)
[WINDIR] => C:\\WINDOWS
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /test.php
[SCRIPT_NAME] => /php/php.exe
[PATH_INFO] => /test.php
[PATH_TRANSLATED] => e:\\server\\test.php
)
[/quote]

To access [INSERT_SOMETHING_HERE] you would do $_SERVER['INSERT_SOMETHING_HERE'] in your script.


[b]Variable Variables[/b]
You can think of Variable Variables as a variable set with the name of a different variable. For example, say you have a variable with your name.

[php]
<?php
$myName = 'Phil';
?>
[/php]
Now, for some reason, you want to set a variable with the value of $myName as the name of it. Doing this is using variable variables. You do it like this
[php]
<?php
$myName = 'Phil';
$$myName = 'This is a variable variable that is named the value of myName! WOW!';
?>
[/php]
Then you could simply do something like
[php]
<?php
$myName = 'Phil';
$$myName = 'This is a variable variable that is named the value of myName! WOW!';
print $Phil;
?>
[/php]

Sure, this may seem completely useless, but in many advanced scripts it has its uses.

Example from php.net
[quote][i]Quoted from php.net[/i]
<?php

$required = array("username", "password");

for ($i = 0; $i < count($required); $i++)
{
if (($$required[$i] == "") || (!$$required[$i]))
{
echo ("Umm... we need $$required[$i]");
}
}

exit();

?>
[/quote]

An finally...

[b]Sessions[/b]
Sessions are a way to store data from one php page to the next without necessarily using cookies. I'm going to use superglobals (Smile). Using them is the newer, preffered, and simpler way of doing them.

Note - Sessions are kind of like cookies in a few way. You need to start the session on EVERY page and put it above all html/output to browser or you will get a header already sent error.

The easiest way to do this is with a simple example scripts.
[php]
<?php
# sessions.php

# lets start the session
session_start();

# lets make a simple page view counter

# have we ever viewed this page before?
if (!isset($_SESSION['count'])) {
# we haven't, so lets set a variable called count and start it at 0
$_SESSION['count'] = 0;
} else {
# we have! lets move the count up one
$_SESSION['count']++;
}
?>
[/php]
Go to that script and reload it a few times.

And thats all there is to the basics of sessions - we started a sessions with session_start, created the variable, and used it on future hits. For more on sessions, check out the [url=http://www.php.net/manual/en/ref.session.php]session page at php.net[/url]

[b]fin.[/b]
Thats the end of my tutorials for now, so use them and be happy. Visit [url=http://www.aesthetic-theory.com]aesthetic-theory[/url] because I'm really cool.

___________________

http://www.philbrodeur.com - Expert PHP Development and Tutorials

Last edited by Phil, June 16th, 2003 03:49 PM (Edited 1 times)

psn

psn

Status: Offline!

Nice little tutorial you have there.. Next we should expect an Essay on PHP 5..

Nah just kidding.

___________________

[WebMobo] [Blog] [Me] [SFX]

phpmonkey

phpmonkey

whoa, wtf?
Status: Offline!

Just a little note Ares,

you run into problems modifying global variables (in some situations)

so its safer to use $GLOBALS["varname"] if you plan to modify the variable.

-Jerome

___________________

Fomerly known as lasnaranjas. Holler.
http://card.mygamercard.net/gelsig/blackdood.png

Phil

Phil

with Mr. Jones
Status: Offline!
Quote:

Originally posted by lasnaranjas
Just a little note Ares,

you run into problems modifying global variables (in some situations)

so its safer to use $GLOBALS["varname"] if you plan to modify the variable.

-Jerome

Never had that problem myself, but i personally try to not use globals. I'll add it to the tutorial Smile

___________________

http://www.philbrodeur.com - Expert PHP Development and Tutorials

CDude

CDude

nothing
Status: Offline!

http://www.php.net/manual/en/language.variables.php

___________________

http://celerondude.com

Phil

Phil

with Mr. Jones
Status: Offline!
Quote:

You know people don't look at the manual.

___________________

http://www.philbrodeur.com - Expert PHP Development and Tutorials

CDude

CDude

nothing
Status: Offline!

Right, answers are for idiots.

___________________

http://celerondude.com

Phil

Phil

with Mr. Jones
Status: Offline!

*points at '5x special olympics champ' title*

Are you trying to say something? Grin

___________________

http://www.philbrodeur.com - Expert PHP Development and Tutorials

phpmonkey

phpmonkey

whoa, wtf?
Status: Offline!

The manual can be hard to read at times thought. Like, untill i got used to the language used in programming books, manpages, etc I was all confused all the time.

Might be kinda hard for a 13 year old.

-jerome

___________________

Fomerly known as lasnaranjas. Holler.
http://card.mygamercard.net/gelsig/blackdood.png

Jeremie

Jeremie

Neversidian
Status: Offline!

i learned most of the php stuff i know from the manual (and from the user comments at the bottom of almost every manual page), and by browsing google

being in these forums for a few weeks already, i understand CDude's "Read the damn manual!!!"

sure the manual is huge, but with a nice search function its easy to find what you are searching for. and for the few cases when the manual doesnt give enough information its *ALWAYS* somewhere on google, or in this forum Shocked

___________________

Jeremie - Used to be the Director of Community Development

Page 1 out of 3
Quick Jump:

Main Navigation


Site & Graphic Design by Aeon Tan
Developed by Jeremie Pelletier & Scott Roach


NeverAPI generated this page in 0.0209 seconds.