Variable in PHP can be declared anywhere in the script. So the scope of the variable is defined by where it can be accessed in the script.
In other words, it is the context where a variable is defined and accessed.
PHP has three different kinds of scopes:
- Local Scope
- Global Scope
- Static Scope
Local Scope
A variable declared inside a function has a local scope. This kind of variables can only be accessed within that function:
Variable with local scope:
<?php function locScope() { $data = "hello"; // local scope echo "<p>local variable value is: $data</p>"; } locScope(); // Using $data outside the function throws an error. echo "<p>Variable outside local scope: $data</p>"; ?>
Global Scope
A variable that is declared outside a function has a global scope. This kind of variables can only be accessed from outside a function:
Variable with global scope:
<?php $data = 120.3; // global scope function gloScope() { // Using $data inside this function throws an error echo "<p>Variable $data inside function is: $data</p>"; } gloScope(); echo "<p>Variable $data outside function is: $data</p>"; ?>
PHP global Keyword
To access the global variable within the function the global keyword is used. Add the global keyword right before the variable:
global keyword
<?php $num1 = 25; $num2 = 20; function glokey() { global $num1, $num2; $result = $num1 + $num2; } glokey(); echo $result; // outputs 45 ?>
PHP static Keyword
Variables are automatically destroyed after the function execution is completed. The static keyword is used if we want to keep the local variable after the function execution.
To do this, use the static keyword in front of the variable:
<?php function static() { static $num = 0; echo $num; $num++; } static();// output is 1 static();// output is 2 static();// output is 3 ?>