PHP Local Scope Vs Global Scope Variables

Notes:

PHP Local scope Vs. Global scope:
- Scope indicates the accessibility and visibility of variables.
- PHP variables will be either in local scope or global scope

Local scope:
- Any variable declared inside a function is considered as in local scope or function scope
- can be accessible only inside that function where it is declared

Note: Local scope variables will be available only in the function execution (i.e. are created as soon as the control enters the function body and deleted as soon as the control exits the function body)

Ex:
function display()
{
$b=20;
echo "b= ", $b,"<br/<"; // 20
}
display();
echo "b= ", $b,"<br/<"; // error: b is not defined

Global scope:
- Any variable declared outside a function is considered as in global scope
- can be accessible anywhere in the script

Note: Global scope variables will be available throughout the script execution

- if you want to access a global scope variable inside a local scope you must use global keyword

Ex 1:
$a=10;
echo "a= ", $a, "<br/<"; // 10
function display()
{
//echo "a= ", $a,"<br/<"; // undefined error
global $a;
echo "a= ", $a,"<br/<"; // 10
}
display();

Ex 2:
$a=10;
echo "a= ", $a, "<br/<"; // 10

$b = 20;
function display()
{
//echo "a= ", $a,"<br/<"; // undefined error
global $a;
echo "a= ", $a,"<br/<"; // 10

$b =30;
echo "b=", $b,"<br/<"; // 30
}
display();

echo "b=", $b,"<br/<"; // 20

Interview Questions:

1. PHP stands for ______________
a. Hypertext Preprocessor
b. Preprocessor Hypertext
c. Personal Home Processor
d. Personal Hypertext processor
Ans: a