How can PHP functions be optimized for recursive operations like the one shown in the code?

PHP functions can be optimized for recursive operations by reducing unnecessary function calls and minimizing memory usage. One way to achieve this is by passing variables by reference instead of by value to avoid creating unnecessary copies of data. Additionally, using static variables within the function can help store and reuse previously computed values, reducing the need for redundant calculations.

function factorial($n, $result = 1) {
    if ($n == 0 || $n == 1) {
        return $result;
    } else {
        $result *= $n;
        return factorial($n - 1, $result);
    }
}

// Example usage
echo factorial(5); // Outputs 120