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 0Write a function
incrementVisit() that increases $visitCount by 1 using the global keywordWrite a function
resetVisit() that sets $visitCount to 0 using the global keywordCall
incrementVisit() twice, then resetVisit(), then incrementVisit() oncePrint 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