In PHP, you can declare variables anywhere in the script.
Variable Scope: Part of the script where variable can be used or allowed to use. If you try to use variables which are not allowed to use in the scope then you will get an error.
There are 3 variable scopes in PHP:
- Local
- Global
- Static
Let's look at those variables one by one. Starting form global:
We declare global variables outside the functions and we can not access them from inside the function.
For example, look at this code:
<?php
$x = "global"; // this variable $x has a global scope
function scope() {
// If we try to use $x inside this function, it will generate an error
echo "<p>I am $x Variable inside the function (I am missing the word global as I can't access the variable)</p>";
}
scope();
echo "<p>I am $x Variable outside the function</p> ";
?>
Take a look at the output in the DEMO link given at the end of this article.
Second one is local variable which you can figure out by name that it's scope will be limited to local function only.
It's because when the function is fully executed, the variables inside that function are deleted.
For example, look at this code:
<?php
function scope2() {
$y = "local"; // this variable $x has a local scope
// If we try to use $x inside this function, it will generate an error
echo "<p>I am $y Variable inside the function</p>";
}
scope2();
echo "<p>I am $y Variable outside the function (I am missing the word local as I can't access the variable)</p> ";
?>
Take a look at the output in the DEMO link given at the end of this article.
Third one is static variable.
I just mentioned in the local variable that when the function is fully executed, the variables inside that function are deleted. But what if we want to save that variable and stop getting deleted?
We need to use static keywords while declaring those variables if we want to save them. However the scope of the variables will be limited ot the function only.
Take a look at this example.
<?php
function statVar() {
static $z = 0;
echo $z;
$z++;
}
statVar(); echo "<br>";
statVar(); echo "<br>";
statVar();
echo "<p>Value of z doesn't stay at 0 everytime the function is called</p>";
?>
Scope variables