Bird
0
0

Consider this PHP code:

hard📝 Application Q9 of 15
PHP - Functions
Consider this PHP code:
$val = 1;
function test() {
  static $val = 0;
  $val++;
  echo $val . ' ';
}
test();
test();
echo $val;

What is the output?
A1 2 2
B1 1 1
C0 1 1
D1 2 1
Step-by-Step Solution
Solution:
  1. Step 1: Analyze static variable behavior inside function

    The static $val inside test() starts at 0 and increments each call, printing 1 then 2.
  2. Step 2: Analyze global variable outside function

    The global $val remains 1, printed after function calls.
  3. Final Answer:

    1 2 1 -> Option D
  4. Quick Check:

    Static inside function increments, global unchanged = 1 2 1 [OK]
Quick Trick: Static variables keep value inside function; globals stay separate [OK]
Common Mistakes:
  • Confusing static and global variables
  • Expecting static variable to reset each call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes