Local and global variables in php with syntax and examples
In PHP, variables are used to store and manipulate data. There are two types of variables: local and global.
Local Variables:
- Declared within a function or block
- Only accessible within that function or block
- Destroyed when the function or block ends
Syntax:
function myFunction() {
$localVariable = 'Hello, World!';
echo $localVariable;
}
Examples:
function greet() {
$name = 'John';
echo "Hello, $name!";
}
greet(); // outputs "Hello, John!"
echo $name; // undefined variable
Global Variables:
- Declared outside of functions or blocks
- Accessible from anywhere in the script
- Persist until the script ends
Syntax:
$globalVariable = 'Hello, World!';
function myFunction() {
global $globalVariable;
echo $globalVariable;
}
Examples:
$greeting = 'Hello, World!';
function greet() {
global $greeting;
echo $greeting;
}
greet(); // outputs "Hello, World!"
echo $greeting; // outputs "Hello, World!"
Static Variables:
- Retain their value between function calls
- Only accessible within the function
Syntax:
function myFunction() {
static $staticVariable = 'Hello, World!';
echo $staticVariable;
}
Examples:
function greet() {
static $greeting = 'Hello, World!';
echo $greeting;
}
greet(); // outputs "Hello, World!"
greet(); // outputs "Hello, World!" again
Superglobals:
- Built-in global variables
- Accessible from anywhere in the script
- Examples: $_GET, $_POST, $_SESSION
Syntax:
echo $_GET['name'];
Examples:
// URL: (link unavailable)
echo $_GET['name']; // outputs "John"
Best Practices:
1. Use local variables for function-specific data.
2. Use global variables for shared data.
3. Use static variables for persistent data.
4. Use superglobals for built-in global variables.
5. Avoid using global variables when possible.
6. Use meaningful variable names.
7. Initialize variables before use.