PHP echo and print Statements
The scope of a variable is defined as its range in the program under which it can be accessed. In other words, "The scope of a variable is the portion of the program within which it is defined and can be accessed."
PHP has three types of variable scopes:
1• Local variable
2• Global variable
3• Static variable
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
Example
Variable with global scope:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
Output
Variable x inside function is:
Variable x outside function is: 5
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
Example
Variable with local scope:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// $x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>// using x outside the function will generate an error</p>";
?>
</body>
</html>
Output
Variable x inside function is: 5
Variable x outside function is:
PHP The global Keyword
The 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):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$x = 10;
function myTest() {
global $x,$y;
$y = $x+$y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
</body>
</html>
Output
15
PHP The static Keyword
Normally, 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:
Example
<!DOCTYPE html>
<html>
<body>
<?php
function myTest(){
static $x =0;
echo $x;
$x++;
}
myTest(); {
echo "<br>";
myTest(); {
echo "<br>";
myTest();
?>
</body>
</html>
Output
0
1
2