0
0
PHPprogramming~5 mins

Global keyword behavior in PHP

Choose your learning style9 modes available
Introduction

The global keyword lets you use variables from outside a function inside that function. It helps share data between different parts of your code.

When you want to change a variable inside a function that was created outside it.
When you need to read or update a value that is shared across multiple functions.
When you want to avoid passing many variables as function parameters.
When you have a setting or counter that many functions should access and modify.
Syntax
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).

Examples
This example shows how the function changes the global variable $number by adding 5.
PHP
<?php
$number = 10;
function addFive() {
    global $number;
    $number += 5;
}
addFive();
echo $number;
The function uses the global $message variable to print a greeting.
PHP
<?php
$message = "Hello";
function greet() {
    global $message;
    echo $message . " World!";
}
greet();
Sample Program

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
<?php
$count = 0;
function increment() {
    global $count;
    $count++;
}
increment();
increment();
echo "Count is: " . $count;
OutputSuccess
Important Notes

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.

Summary

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.