| PHP - Variable Scope | | Print | |
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.
| Users' Comments (0) |
|
No comment posted





