0
0
PHPprogramming~15 mins

Global keyword behavior in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Global keyword behavior
📖 Scenario: Imagine you have a small PHP script that keeps track of a counter. You want to increase this counter inside a function, but the counter is defined outside the function.
🎯 Goal: You will learn how to use the global keyword in PHP to access and modify a variable defined outside a function from inside that function.
📋 What You'll Learn
Create a variable called $counter with the value 0 outside any function.
Create a variable called $increment with the value 5.
Create a function called increaseCounter that uses the global keyword to access $counter and adds $increment to it.
Call the function increaseCounter once.
Print the value of $counter.
💡 Why This Matters
🌍 Real World
Using the <code>global</code> keyword helps when you want to share and update data across different parts of a PHP script, like counters, settings, or shared resources.
💼 Career
Understanding variable scope and the <code>global</code> keyword is important for PHP developers to manage data correctly and avoid bugs in web applications.
Progress0 / 4 steps
1
Create the initial counter variable
Create a variable called $counter and set it to 0.
PHP
Need a hint?

Use $counter = 0; to create the variable.

2
Add the increment variable
Create a variable called $increment and set it to 5.
PHP
Need a hint?

Use $increment = 5; to create the variable.

3
Create the function to increase the counter
Create a function called increaseCounter that uses the global keyword to access $counter and adds $increment to it.
PHP
Need a hint?

Inside the function, write global $counter, $increment; to access the variables, then add $increment to $counter.

4
Call the function and print the counter
Call the function increaseCounter() once, then print the value of $counter using echo.
PHP
Need a hint?

Call increaseCounter(); then print $counter with echo $counter;.