Bird
0
0

What is the issue with this PHP code?

medium📝 Debug Q6 of 15
PHP - Functions
What is the issue with this PHP code?
$total = 5;
function addOne() {
$total = $total + 1;
}
addOne();
echo $total;
AThe variable <code>$total</code> is automatically global inside functions.
BThe variable <code>$total</code> is correctly incremented inside the function.
CThe function should use <code>static</code> keyword instead of <code>global</code>.
DThe function does not access the global variable; it uses an undefined local variable.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable scope

    Inside the function, $total is treated as a local variable but is used before initialization.
  2. Step 2: Missing global keyword

    To modify the global $total, the function must declare global $total;.
  3. Final Answer:

    The function does not access the global variable; it uses an undefined local variable. -> Option D
  4. Quick Check:

    Without global, function uses local undefined variable [OK]
Quick Trick: Declare global to access outside variable [OK]
Common Mistakes:
  • Assuming variables are global by default inside functions
  • Not declaring global before using global variables
  • Confusing static and global keywords

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes