Scope of a variable in php
The scope of the variable tells where we can use the variable in php. The scope of variable are classified into 3 types as follows:
•Local
•Global
•Static
Local variable: The variable which is declared inside a function is called a local variable.It has its scope only inside that function.It means that a variable that declared on a function cannot be used on another function.
Global variable: The variable which is declared outside a function is called a global variable. We cannot access a variable inside a function that is declared outside a function. That is, a variable that we declared outside a function cannot be accessed inside a function without a keyword global.
Static variable: Like java, the php has a feature to free up space/memory automatically after the use/execution of the variable. But sometimes we need to store a variable even after its execution. For that purpose we use the keyword static to declare a static variable that will not be deleted automatically after the execution. The static variable stores a lossless value that can be used a any time.
101
102
103
•Local
•Global
•Static
Local variable: The variable which is declared inside a function is called a local variable.It has its scope only inside that function.It means that a variable that declared on a function cannot be used on another function.
<html>
<head>
</head>
<body>
<?php
function local()
{
$a=5;//this variable is declared locally
echo $a;
}
echo $a;
/*This will be an error because variable
a cannot be used outside a function*/
?>
</body>
</html>
output
5Global variable: The variable which is declared outside a function is called a global variable. We cannot access a variable inside a function that is declared outside a function. That is, a variable that we declared outside a function cannot be accessed inside a function without a keyword global.
<html>
<head>
</head>
<body>
<?php
$a=7;
$b=3;
function global
{
global $a,$b;
$a=$a+$b;
}
echo $a;
?>
</body>
</html>
output
10Static variable: Like java, the php has a feature to free up space/memory automatically after the use/execution of the variable. But sometimes we need to store a variable even after its execution. For that purpose we use the keyword static to declare a static variable that will not be deleted automatically after the execution. The static variable stores a lossless value that can be used a any time.
<html>
<head>
</head>
<body>
<?php
function stvar
{
static $a=100;
echo $a;
$a++;
}
stvar();
stvar();
stvar();
stvar();
?>
</body>
</html>
output
100101
102
103
⇐Prev
Next⇒
Comments
Post a Comment