0
0
PHPprogramming~15 mins

Variable scope in functions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Variable scope in functions
📖 Scenario: Imagine you are managing a small shop's sales system. You want to keep track of the total sales amount and update it when a new sale happens. But you need to understand how variables inside and outside functions behave.
🎯 Goal: You will create a variable to hold the total sales, write a function to add a sale amount, and learn how variable scope works in PHP functions.
📋 What You'll Learn
Create a variable called $totalSales and set it to 0
Create a variable called $newSale and set it to 150
Write a function called addSale that takes one parameter $amount
Inside addSale, add $amount to $totalSales using the global keyword
Call the function addSale with $newSale
Print the value of $totalSales after the function call
💡 Why This Matters
🌍 Real World
Understanding variable scope helps you manage data correctly in programs, like tracking sales or inventory in a shop system.
💼 Career
Many programming jobs require you to write functions that update shared data. Knowing variable scope prevents bugs and makes your code reliable.
Progress0 / 4 steps
1
Create initial sales variables
Create a variable called $totalSales and set it to 0. Then create a variable called $newSale and set it to 150.
PHP
Need a hint?

Use = to assign values to variables. Remember to end each line with a semicolon.

2
Write the addSale function
Write a function called addSale that takes one parameter $amount. Inside the function, use the global keyword to access $totalSales and add $amount to it.
PHP
Need a hint?

Use global $totalSales; inside the function to access the variable outside.

3
Call the addSale function
Call the function addSale with the variable $newSale as the argument.
PHP
Need a hint?

Call the function by writing its name and passing $newSale inside parentheses.

4
Print the total sales
Print the value of $totalSales using echo.
PHP
Need a hint?

Use echo $totalSales; to show the total sales amount.