What is the global keyword in PHP and How to Use It
global keyword allows a function to access variables defined outside its scope, typically in the global scope. It tells PHP to use the global version of the variable instead of creating a new local one inside the function.How It Works
Imagine you have a box (a variable) in your room (the global scope). When you enter a different room (a function), you can't see or use that box directly because each room has its own boxes. The global keyword acts like a special key that lets you open the box from the other room and use what's inside.
Normally, variables inside a function are separate and local to that function. Using global tells PHP to look outside the function and use the variable from the global space. This way, you can read or change the value of a variable defined outside the function.
Example
This example shows how to use the global keyword to access and modify a global variable inside a function.
<?php $counter = 0; function incrementCounter() { global $counter; // Access the global variable $counter++; } incrementCounter(); incrementCounter(); echo $counter; // Outputs 2 ?>
When to Use
Use the global keyword when you need to access or change a variable defined outside a function from within that function. This is common when you want to keep track of a value across multiple function calls without passing it as a parameter.
For example, you might use it to count how many times a function runs, or to share configuration settings across different parts of your code. However, overusing global can make code harder to understand, so it's best used sparingly.
Key Points
- global lets functions access variables outside their local scope.
- Without
global, functions cannot see or change global variables. - Using
globalmodifies the original variable, not a copy. - Overusing
globalcan make code confusing; prefer passing variables as parameters when possible.