If you really need a function to use a global variable, PHP gives you two tools.
1. The global keyword
Write global $name; inside the function. It links the local name to the global variable.
<?php
$counter = 0;
function increase(): void
{
global $counter;
$counter++;
}
increase();
increase();
echo $counter;
2
2. The $GLOBALS array
$GLOBALS is a built-in array that holds every global variable.
<?php
$language = "PHP";
function show(): void
{
echo $GLOBALS["language"];
}
show();
PHP
Why you should avoid both
Global variables work, but they cause trouble in real projects.
- The function secretly depends on something outside it, so you cannot understand it by reading it alone.
- Any code can change the global, so bugs are hard to trace.
- Testing the function is harder.
Compare the two styles:
<?php
// Hidden dependency
$rate = 0.18;
function priceWithTax(float $price): float
{
global $rate;
return $price * (1 + $rate);
}
// Clear dependency
function priceWithTax2(float $price, float $rate): float
{
return $price * (1 + $rate);
}
echo priceWithTax(100) . "\n";
echo priceWithTax2(100, 0.18);
118
118
Same result, but the second version tells you what it needs in its signature.
WordPress uses globals
global $post; or global $wpdb; often. That is how WordPress works. In your own code, prefer parameters.