Friday, January 6, 2012

What is Local Scope in PHP?


When I started out, I also asked what is local scope in PHP. I eventually found out that local scope in PHP relates to the variables. When you setup variables in PHP, you are setting them up in a specific scope. The scope is the range in which the variable is setup.

There are two kinds of scope:


Global Scope - variables that fall in this scope are the ones that is setup outside the functions. Local Scope - variable that fall in this scope are the ones that is setup inside the functions.

Remember that the variables that you setup outside the function cannot be used inside the function.

//Variable in global

$tutorial = "Simple PHP Manual";

//Call function that should print out the variable

write_tutorial();

function write_tutorial() {

//Variable in local

echo $tutorial; //Print out the variable we declared at a global scope

}

The example code above will not display anything because we setup a variable in global scope but we also used the same variable name and used it inside the function (local scope). There are two ways we can take so we can achieve the result that we want.

Passing Arguments

//Variable in global

$tutorial = "Simple PHP Manual";

//Call function passing a variable inside which should echo the variable

write_tutorial($tutorial);

function write_tutorial($parameter) { //Fetch the parameter passed into the function

//Variable in local

echo $parameter; //Echo out the variable we got from the parameter

}

Declaring Global Inside the Function

//Variable in global

$tutorial = "Simple PHP Manual";

//Call function that should print out the variable

write_tutorial();

function write_tutorial() {

//Local scope

//Declare $tutorial as global

global $tutorial; //This line is the key

echo $tutorial; //Print out the variable we declared at a global scope

}




Hopefully you understood what is local scope in PHP. Just remember that local scope is the one inside the functions. I learned PHP the hard way. It took me an insane number of months before I became comfortable in using PHP in my websites. If you want to learn PHP in less than 20 hours, then I suggest you check out this Simple PHP review at http://www.squidoo.com/simple-php-review


No comments:

Post a Comment