In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
<?php
$a = 5; // Global scope
// variable declared outside function
function myFunction() {
$b = 7; //Local scope
// variable declared inside function
}
?>
In the example, there are two variables $a
and $b
and a function myTest()
.
$a
is a global variable since it is declared outside the function and $b
is a local variable since it is created inside the function.
<?php
$a = 5; // global scope
function myTest() {
$b = 7; // local scope
echo "<p>Test variables inside the function:</p>";
echo "Variable a is: $a";
echo "<br />";
echo "Variable b is: $b";
}
myTest();
echo "<p>Test variables outside the function:</p>";
echo "Variable a is: $a";
echo "<br />";
echo "Variable b is: $b";
?>
When we output the values of the two variables inside the myTest() function, it prints the value of $b as it is the locally declared, but cannot print the value of $a since it is created outside the function.
Then, when we output the values of the two variables outside the myTest() function, it prints the value of $a, but cannot print the value of $b since it is a local variable and it is created inside the myTest() function.
Test variables inside the function:
Variable a is:Test variables outside the function:
Variable a is: 5The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
<?php
$a = 5; // global scope
function myTest() {
global $a; //access global variable with global keyword
$b = 7; // local scope
echo "<p>Test variables inside the function:</p>";
echo "Variable a is: $a";
echo "<br />";
echo "Variable b is: $b";
}
myTest();
?>
Test variables inside the function:
Variable a is: 5Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
<?php
function myStaticTest() {
static $a = 0; // use of static keyword
echo $a ;
$a++;
}
myStaticTest();
myStaticTest();
myStaticTest();
?>
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.
Just remove static keyword from example, and run it again. if you want to see difference!
Ask Question