W3docs

global

The "global" keyword is used in PHP to access a variable declared outside the current function or class. In this article, we will explore the syntax and usage

The PHP "global" Keyword: A Comprehensive Guide

The "global" keyword is used in PHP to access a variable declared outside the current function or class. In this article, we will explore the syntax and usage of the "global" keyword in depth, and provide plenty of examples to help you master this important PHP feature.

Syntax

The "global" keyword is used to access a global variable in PHP. Here is the basic syntax for using the "global" keyword:

The PHP syntax of global

<?php
$variableName = "initial value";

function functionName() {
  global $variableName;
  // code to be executed
}

In this example, the "global" keyword is used to access a variable called $variableName that is declared outside the current function.

Examples

Let's look at some practical examples of how the "global" keyword can be used:

Examples of PHP global

<?php

// Example 1
$counter = 0;

function incrementCounter()
{
  global $counter;
  $counter++;
}

incrementCounter();
echo $counter . PHP_EOL; // Output: 1

// Example 2
$color = "red";

function changeColor()
{
  global $color;
  $color = "blue";
}

changeColor();
echo $color; // Output: blue

In these examples, we use the "global" keyword to access variables declared outside the current function and modify their values.

Benefits

Using the "global" keyword has several benefits, including:

  • Access to global variables: The "global" keyword allows you to access and modify variables declared outside the current function or class.
  • Note on maintainability: While global provides direct access to outer scope variables, overusing it can make code harder to debug and test. Modern PHP development often prefers passing variables as function parameters, using dependency injection, or accessing the $GLOBALS superglobal array when necessary.

Conclusion

In conclusion, the "global" keyword allows PHP developers to access variables declared outside the current function or class. While it can be useful for quick scripts or legacy code, modern PHP best practices recommend limiting its use to avoid tight coupling and maintainability issues. For better architecture, consider passing variables as parameters, using dependency injection, or leveraging the $GLOBALS superglobal array. We hope this guide has been helpful as you continue to develop your PHP skills.

Practice

Practice

What is true about the variable scope in PHP, based on the content of the specified URL?