
PHP | What are the scopes of variables in PHP?
Scopes define the visibility of a variable. In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be used.
There are three scopes available in PHP
- global
- local
- static
global
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
we can use a global variable within a function by using the "global" keyword.
<?php
$x = 25;
$y = 10;
function test() {
global $x, $y;
$y = $x + $y;
}
test();
echo $y;
?>
// outputs will be 35
local
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
static
Normally, when a function is executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable.