0
0
PhpConceptBeginner · 3 min read

What is the global keyword in PHP and How to Use It

In PHP, the 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
<?php
$counter = 0;

function incrementCounter() {
    global $counter; // Access the global variable
    $counter++;
}

incrementCounter();
incrementCounter();

echo $counter; // Outputs 2
?>
Output
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 global modifies the original variable, not a copy.
  • Overusing global can make code confusing; prefer passing variables as parameters when possible.

Key Takeaways

The global keyword allows functions to access and modify variables from the global scope.
Without global, variables inside functions are local and separate from global variables.
Use global when you need shared state but avoid overusing it to keep code clear.
Passing variables as function parameters is often a cleaner alternative to global.