The global keyword lets you use variables from outside a function inside that function. It helps share data between different parts of your code.
Global keyword behavior in PHP
function example() { global $variableName; // Now $variableName refers to the global variable }
You must declare each global variable inside the function with the global keyword.
It is used inside functions and class methods to access global variables (not class properties).
$number by adding 5.<?php $number = 10; function addFive() { global $number; $number += 5; } addFive(); echo $number;
$message variable to print a greeting.<?php $message = "Hello"; function greet() { global $message; echo $message . " World!"; } greet();
This program uses the global keyword to increase the $count variable inside the function. It calls the function twice, so the count becomes 2.
<?php $count = 0; function increment() { global $count; $count++; } increment(); increment(); echo "Count is: " . $count;
Using many global variables can make your code harder to understand and debug.
Consider passing variables as function arguments when possible for clearer code.
Global variables keep their values between function calls unless changed.
The global keyword lets functions access variables defined outside them.
You must declare each global variable inside the function to use it.
Use global variables carefully to keep your code clean and easy to follow.