PHP Variable Scopes

0
31

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:

[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]


 

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]

 

Leave a Reply

Be the First to Comment!

Notify of
wpDiscuz