Online
 
Thursday, 20 November 2008
 
 

PHP - Variable Scope | Print |  E-Mail
 

PHP -  Variable Scope

The scope of a variable is the context within which a variable is available. There are two scopes for variables in PHP. Global variables are available directly from the mainline PHP execution. That is, if you are not inside a function, you can access global variables directly. Unlike most other languages, functions in PHP have their own, completely separate variable scope. Take this example:

<?php
function test( ) {
echo $a;
}

$a = "Hello World";
test( );
?>

If you run this script you will find that there is no output. This is because the $a you are trying to access inside the test( ) function is a completely different variable from the global $a you created in the global scope just before calling the function. In order to access a globally-scoped variable from inside a function, you need to tell the function to use the global scope for that particular variable. It can be done with the global keyword like this:

<?php
function test( ) {
global $a;
echo $a;
}

$a = "Hello World";
test( );
?>

Alternatively, you can use the $GLOBALS array like this:

<?php
function test( ) {
echo $GLOBALS['a'];
}

$a = "Hello World";
test( );
?>

In this last example, the $GLOBALS array is known as a superglobal, which is a variable that is automatically available in all scopes without needing to be declared global in order to be accessed from within a function.

 

 

This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Rokok Kretek Jumbo Coklat

“Terbuat dari tembakau, saos dan cengkeh pilihan kwalitas tinggi sehingga menghasilkan rokok dengan rasa yang cocok untuk segala cuaca”
Jumbo Coklat - Powered By G-Ads

 
Top! Top!