Are there any alternative methods to access variables defined in one function from another function in PHP?

When trying to access variables defined in one function from another function in PHP, one common approach is to use global variables. By declaring the variable as global in both functions, you can access and modify its value across different functions. However, it is generally recommended to avoid using global variables as they can make code harder to maintain and debug. An alternative method is to pass the variable as a parameter to the function where it is needed.

// Using global variables
$globalVar = 10;

function function1() {
    global $globalVar;
    echo $globalVar; // Output: 10
}

function function2() {
    global $globalVar;
    $globalVar = 20;
}

function1();
function2();
echo $globalVar; // Output: 20