Variables Scope in PHP : Explained in easy language

Variables Scope in PHP

There are three types of variable scopes in PHP .  They are as follows:

1)      Local

2)      Global

3)      Static

Local Scope : When a variable declared inside a function (has a local scope ) and it can only be accessed within that function, the variable is called as local scope variable .

E.g.

<?php

function localvar()

{

$x=6; //local scope variable

echo "Variable x inside function is : $x";

}

localvar();

echo "Variable x outside function is : $x";//generate an error like undefined variable

?>

 

Output:  

Variable x inside function is : 6

Notice: Undefined variable: x

Variable x inside function is :

 

Global Scope : When a variable declared outside a function (has a global scope) and it can only be accessed outside a function, the variable is called as global scope variable .

E.g.

 <?php

$x=10; //global scope

function globalvar()

{

echo "Variable x inside function is : $x";//generate an error like undefined variable

}

globalvar();

echo "Variable x outside function is : $x";

?>

Output:

Notice: Undefined variable x

Variable x inside function is :

Variable x outside function is : 10

Global Keyword : By using global keyword we can access a global variable within a function. Just add or write global keyword before the variables inside the function. As follows,

e.g.

<?php

$x=10; //global scope

function globalvar()

{

            global $x;//By using global keyword

echo "Variable x inside function is : $x<br>";

}

globalvar();

echo "Variable x outside function is : $x";

?>

Output :

Variable x inside function is : 10

Variable x outside function is : 10

 

Static Scope : When a function is executed , all of its variables are deleted. However we want a local variable not to be deleted. We need it for further job. Use the static keyword when you first declared the variable . Then each time the function is called , the variable will still have the information it contained from the last time the function called.

e.g.

<?php

function scopevar (){

            static $x=11;

            echo $x;

            $x++;

}

scopevar ();

echo "<br>";

scopevar();

echo "<br>";

scopevar ();

?>

Output :

11

12

13

     

              In that way we learn variables scope in short .

Note: Read this blog regularly for important concepts and interview questions.

This blog is useful for IT students, IT freshers, BCA/MCA freshers. This blog contains Resume Tips, interview questions with answers.

1 comment:

  1. I have read your blog it’s very attractive and impressive. I like it your blog.
    Click for this

    ReplyDelete

We are here to listen you, Comment your valueable opinion...!!!