PHP's most used variable scopes are:
- local
- global
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
<?php
$name = "Tornike"; // global scope
function greeting() {
echo "Hello " . $name . "!"; // using $name will generate an error
}
greeting();
echo "Hello" . $name . "!"; // using $name will generate output (Hello Tornike!)
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php
function greeting() {
$name = "Tornike"; // local scope
echo "Hello " . $name . "!"; // using $name inside the function will generate output (Hello Tornike!)
}
greeting();
echo "Hello" . $name . "!"; // using $name outside the function will generate an error
?>