What are the potential pitfalls of referencing globals or superglobals within functions in PHP?

Referencing globals or superglobals within functions in PHP can lead to code that is tightly coupled and difficult to maintain. It can also make the code harder to test and reuse. To solve this issue, it is recommended to pass the necessary variables as arguments to the function instead of relying on globals or superglobals.

// Incorrect way of referencing a global variable within a function
$globalVar = 'Hello';

function printGlobalVar() {
    global $globalVar;
    echo $globalVar;
}

printGlobalVar(); // Output: Hello

// Correct way of passing the variable as an argument to the function
$globalVar = 'Hello';

function printVar($var) {
    echo $var;
}

printVar($globalVar); // Output: Hello