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 0Create a variable called
$newSale and set it to 150Write a function called
addSale that takes one parameter $amountInside
addSale, add $amount to $totalSales using the global keywordCall the function
addSale with $newSalePrint 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