Skip to content

PHP Tutorial Variables and Constants

The global Keyword and $GLOBALS

Lesson 29 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
$counter = 0;

function increase(): void
{
    global $counter;
    $counter++;
}

increase();
increase();

echo $counter;
Output
OUTPUT
2

2. The $GLOBALS array

$GLOBALS is a built-in array that holds every global variable.

index.php
PHP
<?php
$language = "PHP";

function show(): void
{
    echo $GLOBALS["language"];
}

show();
Output
OUTPUT
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:

index.php
PHP
<?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);
Output
OUTPUT
118
118

Same result, but the second version tells you what it needs in its signature.

info
WordPress uses globals
In WordPress code you will see global $post; or global $wpdb; often. That is how WordPress works. In your own code, prefer parameters.