0
0
PHPprogramming~20 mins

Why global state is dangerous in PHP - See It in Action

Choose your learning style9 modes available
Why Global State is Dangerous in PHP
📖 Scenario: Imagine you are building a simple PHP application that tracks user visits. You want to understand how using global variables can cause problems when multiple parts of your program change the same data unexpectedly.
🎯 Goal: You will create a PHP script that uses a global variable to count visits, then see how changing it in different functions can lead to confusing results. This will help you learn why global state is dangerous and how to avoid it.
📋 What You'll Learn
Create a global variable called $visitCount initialized to 0
Write a function incrementVisit() that increases $visitCount by 1 using the global keyword
Write a function resetVisit() that sets $visitCount to 0 using the global keyword
Call incrementVisit() twice, then resetVisit(), then incrementVisit() once
Print the final value of $visitCount
💡 Why This Matters
🌍 Real World
Many PHP applications use global variables to share data, but this can cause bugs when different parts of the code change the same data unexpectedly.
💼 Career
Understanding why global state is dangerous helps developers write cleaner, more reliable PHP code, which is important for maintaining and scaling web applications.
Progress0 / 4 steps
1
Create the global variable $visitCount
Create a global variable called $visitCount and set it to 0.
PHP
Need a hint?

Use $visitCount = 0; outside any function to create a global variable.

2
Write the functions incrementVisit() and resetVisit()
Write a function called incrementVisit() that uses the global keyword to access $visitCount and adds 1 to it. Also write a function called resetVisit() that uses the global keyword to set $visitCount back to 0.
PHP
Need a hint?

Inside each function, use global $visitCount; to access the global variable.

3
Call the functions in order
Call incrementVisit() twice, then call resetVisit(), then call incrementVisit() once.
PHP
Need a hint?

Call the functions exactly in this order: incrementVisit(), incrementVisit(), resetVisit(), incrementVisit().

4
Print the final value of $visitCount
Print the value of the global variable $visitCount using echo.
PHP
Need a hint?

Use echo $visitCount; to show the final count.