Bird
Raised Fist0
PHPprogramming~10 mins

Why global state is dangerous in PHP - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why global state is dangerous in PHP
Start: Global variable set
↓
Function A reads/modifies global
↓
Function B reads/modifies global
↓
Unexpected changes in global
↓
Hard to track bugs
↓
Program behaves unpredictably
Global variables can be changed anywhere, causing unexpected results and bugs that are hard to find.
Execution Sample
PHP
<?php
$counter = 0;
function increment() {
  global $counter;
  $counter++;
}
increment();
increment();
echo $counter;
?>
This code uses a global variable $counter that a function increments twice, showing how global state changes.
Execution Table
StepActionGlobal $counter ValueOutput
StartInitialize $counter = 00
Call increment() #1Increment $counter by 11
Call increment() #2Increment $counter by 12
Echo $counterPrint current $counter value22
💡 Program ends after printing the final value of $counter which is 2
Variable Tracker
VariableStartAfter increment() #1After increment() #2Final
$counter0122
Key Moments - 2 Insights
Why can changing a global variable in one function affect another function unexpectedly?
Because both functions use the same global variable, changes in one affect the shared state seen by the other, as shown in steps 2 and 3 of the execution_table.
Why is it hard to find bugs when using global variables?
Because any part of the code can change the global variable at any time, making it unclear where a wrong value came from, as the global $counter changes in multiple places.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $counter after the first call to increment()?
A1
B0
C2
DUndefined
💡 Hint
Check the 'Global $counter Value' column at step 'Call increment() #1'
At which step does the program output the value 2?
AStart
BEcho $counter
CCall increment() #1
DCall increment() #2
💡 Hint
Look at the 'Output' column in the execution_table
If we remove the 'global' keyword inside increment(), what happens to $counter?
A$counter increments globally as before
BError: undefined variable
C$counter inside function is local and global $counter stays 0
DProgram crashes
💡 Hint
Without 'global', the function uses a local variable, so global $counter does not change (see variable_tracker)
Concept Snapshot
Global variables in PHP can be accessed and changed anywhere using the 'global' keyword.
This shared state can cause unexpected bugs because changes in one place affect others.
Tracking bugs is hard since any function can modify the global variable.
Avoid globals for safer, predictable code by passing variables as parameters instead.
Full Transcript
This example shows a global variable $counter initialized to 0. Two calls to the function increment() increase $counter by 1 each time using the global keyword. The execution table traces each step: starting at 0, after first increment it becomes 1, after second increment it becomes 2, and finally the program prints 2. The variable tracker shows $counter changing from 0 to 2 across calls. Beginners often get confused because changes in one function affect the global state seen by others, making bugs hard to find. The quiz asks about $counter values at different steps and what happens if the global keyword is removed. The key lesson is that global state is dangerous because it can be changed anywhere, causing unpredictable behavior and making debugging difficult.

Practice

(1/5)
1. Why is using global variables considered dangerous in PHP?
easy
A. Because they can be changed anywhere, causing unexpected bugs
B. Because they make the code run faster
C. Because they prevent the use of functions
D. Because they automatically encrypt data

Solution

  1. Step 1: Understand what global variables do

    Global variables can be accessed and modified from any part of the program.
  2. Step 2: Identify the risk of global variables

    Since they can be changed anywhere, it is easy to accidentally overwrite or misuse them, leading to bugs that are hard to find.
  3. Final Answer:

    Because they can be changed anywhere, causing unexpected bugs -> Option A
  4. Quick Check:

    Global variables cause unexpected bugs [OK]
Hint: Global variables can be changed anywhere, causing bugs [OK]
Common Mistakes:
  • Thinking global variables improve performance
  • Believing global variables prevent function use
  • Assuming global variables encrypt data automatically
2. Which of the following is the correct way to access a global variable inside a PHP function?
easy
A. Declare the variable again inside the function
B. Use the global keyword inside the function
C. Use static keyword inside the function
D. Use const keyword inside the function

Solution

  1. Step 1: Recall PHP syntax for accessing global variables

    In PHP, to access a global variable inside a function, you must declare it with the global keyword.
  2. Step 2: Understand why other options are incorrect

    Declaring the variable again inside the function creates a new local variable. static keeps value between calls but does not access global. const defines constants, not variables.
  3. Final Answer:

    Use the global keyword inside the function -> Option B
  4. Quick Check:

    Access global variable in function = global keyword [OK]
Hint: Use 'global' keyword inside function to access globals [OK]
Common Mistakes:
  • Redeclaring variable inside function thinking it accesses global
  • Using static or const keywords incorrectly
  • Forgetting to declare global keyword inside function
3. What will be the output of this PHP code?
$count = 5;
function increment() {
global $count;
$count++;
}
increment();
echo $count;
medium
A. 5
B. Nothing is printed
C. Error: Undefined variable
D. 6

Solution

  1. Step 1: Understand the global keyword usage

    The function declares global $count; which means it uses the global variable $count defined outside.
  2. Step 2: Trace the code execution

    The global $count starts at 5, the function increments it by 1, so $count becomes 6. Then echo $count; prints 6.
  3. Final Answer:

    6 -> Option D
  4. Quick Check:

    Global increment changes $count to 6 [OK]
Hint: Global keyword lets function modify external variable [OK]
Common Mistakes:
  • Thinking $count inside function is local without global keyword
  • Expecting output 5 because of misunderstanding scope
  • Assuming code causes error due to variable scope
4. Identify the problem in this PHP code related to global state:
$value = 10;
function changeValue() {
$value = 20;
}
changeValue();
echo $value;
medium
A. The function changes the global variable correctly
B. The code will cause a syntax error
C. The function does not change the global variable because it lacks the global keyword
D. The variable $value is undefined

Solution

  1. Step 1: Analyze variable scope in the function

    Inside the function, $value = 20; creates a new local variable, not affecting the global $value.
  2. Step 2: Understand why global keyword is needed

    Without declaring global $value; inside the function, the global variable remains unchanged.
  3. Final Answer:

    The function does not change the global variable because it lacks the global keyword -> Option C
  4. Quick Check:

    Missing global keyword means global variable unchanged [OK]
Hint: Without 'global', function changes local variable only [OK]
Common Mistakes:
  • Assuming function changes global variable without global keyword
  • Expecting syntax error when none occurs
  • Thinking $value is undefined outside function
5. You have a PHP script that uses a global variable $config to store settings. Why is this approach risky, and what is a better alternative?
hard
A. Global $config can be changed anywhere causing bugs; better to pass it as a function parameter
B. Global variables are faster; no alternative needed
C. Global $config encrypts data automatically; better to use global for security
D. Global variables prevent code reuse; better to use global constants instead

Solution

  1. Step 1: Understand risks of global variables for configuration

    Global $config can be modified anywhere, leading to unexpected changes and bugs.
  2. Step 2: Identify better practice

    Passing $config explicitly as a function parameter keeps control clear and avoids accidental changes.
  3. Final Answer:

    Global $config can be changed anywhere causing bugs; better to pass it as a function parameter -> Option A
  4. Quick Check:

    Pass config as parameter to avoid global bugs [OK]
Hint: Pass config as parameter instead of using global variable [OK]
Common Mistakes:
  • Believing global variables improve speed or security
  • Thinking global constants solve all global state issues
  • Ignoring risks of accidental global variable changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard