Bird
0
0

You want to avoid global state in PHP but need to share a counter across functions. Which approach is best?

hard📝 Application Q8 of 15
PHP - Request Lifecycle
You want to avoid global state in PHP but need to share a counter across functions. Which approach is best?
ADeclare the counter as a global variable and access it everywhere
BUse a class with a private property and public methods to manage the counter
CUse a static variable inside a function to keep count
DPass the counter as a global variable to every function manually
Step-by-Step Solution
Solution:
  1. Step 1: Understand why global state is bad

    Global variables cause hidden dependencies and bugs.
  2. Step 2: Evaluate alternatives

    Using a class with private property encapsulates state and controls access safely.
  3. Final Answer:

    Use a class with a private property and public methods to manage the counter -> Option B
  4. Quick Check:

    Encapsulation avoids global state problems [OK]
Quick Trick: Encapsulate shared data in classes, not globals [OK]
Common Mistakes:
  • Using global variables for shared state
  • Relying on static variables which are less flexible
  • Passing globals manually is error-prone

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes