0% found this document useful (0 votes)
4 views3 pages

Variable Scope

Uploaded by

dcsamaldacollege
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Variable Scope

Uploaded by

dcsamaldacollege
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

3.

Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before the
variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the
scope. Understand it with the help of an example:
Example:
File: static_variable.php
1. <?php
2. function static_var()
3. {
4. static $num1 = 3; //static variable
5. $num2 = 6; //Non-static variable
6.
7. $num1++;
8.
9. $num2++;
10. echo "Static: " .$num1 ."</br>";
11. echo "Non-static: " .$num2 ."</br>";
12. }
13.
14. //first function call
15. static_var();
16.
17. //second function call
18. static_var();
19. ?>
Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

We have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is why because
$num1 is not a static variable, so it freed its memory after the execution of each function call.

You might also like