Sobes.tech
Junior

What is the purpose of the word 'global' in PHP?

sobes.tech AI

Answer from AI

The global keyword in PHP is used to access and modify variables from the global scope within a function.

By default, variables declared inside a function are local and not visible outside of it. Using global, you can explicitly specify that you want to use a variable declared outside the current function.

Example:

<?php

$globalVariable = "This is a global variable";

function accessGlobal() {
    global $globalVariable; // Access to the global variable
    echo $globalVariable;
    $globalVariable = "Value changed from the function"; // Modify the global variable
}

accessGlobal(); // Will output "This is a global variable"
echo $globalVariable; // Will output "Value changed from the function"

?>

An alternative way to access global variables is by using the superglobal array $GLOBALS.

<?php

$globalVariable = "This is a global variable";

function accessGlobalWithGLOBALS() {
    echo $GLOBALS['globalVariable'];
    $GLOBALS['globalVariable'] = "Value changed from the function via GLOBALS";
}

accessGlobalWithGLOBALS(); // Will output "This is a global variable"
echo $globalVariable; // Will output "Value changed from the function via GLOBALS"

?>

Using $GLOBALS is often considered more explicit and preferable, as it does not require declaring global for each variable and allows you to get a list of all global variables.

Be cautious when using global frequently, as it can make testing the code more difficult, reduce predictability, and increase coupling between functions. Passing necessary data to functions as arguments is a more recommended practice.

What is the purpose of the word 'global' in PHP? — PHP - sobes.tech