Oct
09
2008

Functions: Variable Scope

If you create a variable in the global scope (in main script, outside of a function) then the value of that variable is not available within the function unless passed to it trough constants, arguments or using superglobals.

List of Superglobal’s

$_GET - receaves data sent to php via script url (?page=1)
$_POST - receaves data sent to php via posting form
$_FILES - receaves data from post file uploads
$_COOKIE - receaves data sent to PHP via HTTP cookies
$_REQUEST - receaves data sent via $_COOKIE,$_POST and $_GET
$_SESSION - receaves data avaliable from previosly stored session
$_SERVER - receaves server information
$_ENV - receaves data avaliable from the PHP environment
and the use of global or $GLOBALS['variable']

Superglobal’s in Functions

In functions you can use any of the superglobal’s above this means you can use functions to receive user data from url, forms and attachments or data stored such as cookies, sessions and server information.

GLOBAL Superglobal in Functions

Once you create a new function it contains no data unless passed to it. If you require contents that is in the global scope you can use the superglobal array. Here are three examples of functions:

$a = "Hello";
$b = "World";
function hello_one(){
echo "$a $b";
}
function hello_two($a,$b){
echo "$a $b";
}
function hello_three(){
global $a, $b; //Using Superglobal
echo "$a $b";
}
 
hello_one(); // Displays warning
hello_two(); // Outputs "Hello World" by passing variables in arguments
hello_three(); // Outputs "Hello World" using superglobal

As you can see you can use global and variable names separated by a comma to make them available in the function.

Constants in Functions

Something I recently learned is that Constants are passed to functions by default, this means that any constant in the globalscope is available in the function scope.

define('WEBURL', "http://zend.is-hacked.com");
function footer(){
return 'Thank you for visiting '.WEBURL;
}
echo footer()

As you can are now aware constants are passed to function scope and therefore the output from the script will be “Thank you for visiting http://zend.is-hacked.com”.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS