0
0
PHPprogramming~20 mins

Why global state is dangerous in PHP - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Global State Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code with global state?

Consider this PHP code that uses a global variable. What will it print?

PHP
<?php
$counter = 0;
function increment() {
    global $counter;
    $counter++;
}
increment();
increment();
echo $counter;
?>
A2
B0
C1
DError: Undefined variable
Attempts:
2 left
💡 Hint

Remember that global keyword allows access to the variable outside the function.

🧠 Conceptual
intermediate
1:30remaining
Why can global state cause bugs in PHP?

Which of the following is the main reason global state is dangerous in PHP?

AGlobal variables are slower to access than local variables
BGlobal variables can be changed anywhere, making code unpredictable
CPHP does not support global variables
DGlobal variables automatically reset after each function call
Attempts:
2 left
💡 Hint

Think about how many parts of a program can change a global variable.

🔧 Debug
advanced
2:00remaining
What error does this PHP code cause due to global state misuse?

Look at this PHP code snippet. What error will it produce?

PHP
<?php
function addOne() {
    $count++;
}
addOne();
echo $count;
?>
AParse error: syntax error
BFatal error: Cannot access global variable
CNotice: Undefined variable $count
DOutput: 1
Attempts:
2 left
💡 Hint

Is $count defined inside the function?

🚀 Application
advanced
2:00remaining
How to avoid global state issues in PHP?

Which approach helps avoid problems caused by global state in PHP?

AUse function parameters and return values instead of global variables
BDeclare all variables as global to keep them consistent
CUse global variables only inside classes
DAvoid using functions to keep variables local
Attempts:
2 left
💡 Hint

Think about how to keep data flow clear and controlled.

Predict Output
expert
2:30remaining
What is the output of this PHP code demonstrating global state side effects?

Analyze this PHP code. What will it output?

PHP
<?php
$val = 5;
function multiply() {
    global $val;
    $val *= 2;
}
multiply();
multiply();
echo $val;
?>
A10
BError: Undefined variable
C5
D20
Attempts:
2 left
💡 Hint

Each call doubles the value of $val.