PHP Variables Scopes
In PHP Variable can declare anywhere in the script.
[sam id=”4″ codes=”true”]
PHP has three different variables scope:
- local
- blobal
- static
Global and Local Scope
A Variable declare outside a function has a global scope and can only be access outside a function.
A Variable declare within a function has a local scope and can only be access within that function:
[nextpage title=”Program” ]
[message_box color=”yellow”]
<html>
<body>
<?php
$x=10; // global scope
function myTest() {
$x = 5; // local scope
echo “<p>Variable x inside function is: $x</p>”;
}
myTest();
echo “<p>Variable x outside function is: $x</p>”;
?>
</body>
</html>
[/message_box]
[/nextpage]
[nextpage title=”Output” ]
[message_box color=”yellow”]
Variable x inside function is: 5
Variable x outside function is: 10
[/message_box]
[/nextpage]
PHP The Static Keyword
Normally, when a function is completed/executed all of its variable are deleted.However sometime we want a local variable not to be deleted.We need it further job.
[message_box color=”yellow”]
<html>
<body>
<?php
function test()
{
static $x = 0;
echo $x;
$x++;
}
test();
echo “<br>”;
test();
echo “<br>”;
test();
echo “<br>”;
test();
echo “<br>”;
test();
?>
</body>
</html>
[/message_box]
[message_box color=”yellow”]
0
1
2
3
4
[/message_box]