Consider this PHP code that uses a global variable. What will it print?
<?php $counter = 0; function increment() { global $counter; $counter++; } increment(); increment(); echo $counter; ?>
Remember that global keyword allows access to the variable outside the function.
The global keyword inside increment() lets the function access and modify the $counter variable declared outside. Each call increases it by 1, so after two calls, it becomes 2.
Which of the following is the main reason global state is dangerous in PHP?
Think about how many parts of a program can change a global variable.
Global variables can be modified from any part of the program, which makes it hard to track changes and can cause unexpected bugs.
Look at this PHP code snippet. What error will it produce?
<?php function addOne() { $count++; } addOne(); echo $count; ?>
Is $count defined inside the function?
The variable $count is not declared or marked global inside the function, so PHP treats it as undefined, causing a notice.
Which approach helps avoid problems caused by global state in PHP?
Think about how to keep data flow clear and controlled.
Passing data through function parameters and returning results keeps variables local and predictable, reducing bugs from global state.
Analyze this PHP code. What will it output?
<?php $val = 5; function multiply() { global $val; $val *= 2; } multiply(); multiply(); echo $val; ?>
Each call doubles the value of $val.
The global variable $val starts at 5. Each call to multiply() doubles it: 5 → 10 → 20.