In the last lesson you passed values into functions and got answers back out. That handoff is not just a convenience: it is how a function keeps its own work separate from the rest of your program. The rule that governs where a variable can be seen is called scope, and once you understand it, a whole class of confusing bugs disappears.
What Is Scope?
Scope is the answer to a simple question: from where can this variable be seen? In PHP the main rule is this: a variable created inside a function lives only inside that function. When the function finishes, that variable is gone. Code outside the function cannot see it, and, just as importantly, the function cannot see the variables outside it either.
Think of a function as a room with the door closed. Whatever you write on the whiteboard inside the room stays in the room. People in the hallway cannot read it, and you cannot read theirs. Each function gets its own private whiteboard.
<?php
function greet() {
$message = "Hello from inside";
echo $message;
}
greet();
Hello from inside
Here $message is a local variable. It exists while greet() runs and nowhere else. Try to echo $message after the function call and PHP would warn you that it is undefined, because out in the hallway that name means nothing.
Why Separate Scopes Are a Good Thing
At first this feels like a restriction. It is actually a gift. Because each function has its own private space, you can reuse common names like $total, $i, or $result inside many different functions without them ever clashing. A $count in one function has nothing to do with a $count in another. You never have to worry that calling a function will secretly change a variable you are using somewhere else.
The classic surprise is expecting a function to reach out and change a variable outside it. It does not. Make a prediction before you run this:
What does this print?
<?php
$score = 10;
function resetScore() {
$score = 0;
}
resetScore();
echo $score;
- 10
- 0
- Nothing
The $score inside resetScore() is a brand new local variable that happens to share the name. Setting it to 0 does not touch the outer $score, so the outer one is still 10.
Two variables, same name, two different whiteboards. The one inside the function was created fresh, changed, and thrown away when the function ended. The outer one never moved.
The Right Pattern: In With Arguments, Out With Return
So if a function cannot see your variables, how do you give it what it needs, and how do you get its answer back? Exactly the way you learned last lesson: pass data in as arguments, and hand data back with return. This is the clean doorway into and out of the room.
<?php
function double($number) {
return $number * 2;
}
$price = 5;
$doubled = double($price);
echo $doubled;
10
Read the flow: $price goes in as the argument $number, the function does its work on its own copy, and the result comes out through return. You catch that result in $doubled. The function never needed to see $price directly, and it left every one of your outside variables untouched. This is the pattern to reach for almost every time.
The global Keyword, and Why to Avoid It
PHP does offer a way to pull an outside variable into a function: the global keyword. It tells the function to use the variable from the outer scope instead of making a local one.
<?php
$count = 0;
function addOne() {
global $count;
$count++;
}
addOne();
echo $count;
1
It works, but it quietly reintroduces the exact problem that scope protects you from. Now addOne() secretly depends on a variable defined somewhere else, and calling it changes that variable behind the scenes. In a small script this seems harmless. In a larger one it makes bugs hard to trace, because you can no longer tell what a function touches just by reading its inputs and outputs.
Do not rely on global. A function that reaches out to grab outside variables is hard to reason about and easy to break. Pass what it needs in as arguments, and send its result back with return. The double example above does the same job as the global one, and it hides nothing.
Static Variables That Remember
There is one useful exception to “local variables vanish when the function ends.” If you mark a local variable as static, PHP keeps its value between calls. The variable is still private to the function, but instead of starting fresh each time, it remembers where it left off.
<?php
function nextId() {
static $id = 0;
$id++;
return $id;
}
echo nextId();
echo nextId();
echo nextId();
123
The line static $id = 0; runs its assignment only on the very first call. After that, PHP skips the assignment and reuses the value it kept, so $id climbs 1, 2, 3 across the three calls. Without static, $id would be reset to 0 every time and each call would return 1. A static variable is handy whenever a function needs to count how many times it has run or remember something from its last call, all without exposing that state to the rest of your program.
A variable is created inside a function with a normal assignment. Where can it be used?
- Only inside that function
- Anywhere in the whole script
- Inside any other function too
A variable assigned inside a function is local to that function. Code outside it, and other functions, cannot see it. To share a value, pass it in as an argument or return it.
Your Turn
Write a function called triple that takes one number as an argument and returns it multiplied by 3. Then call it with 10 and echo the result, so the output is exactly 30. Then hit Check my answer.
<?php
function triple($number) {
}
<?php
function triple($number) {
return $number * 3;
}
echo triple(10);
What You Learned
- A variable made inside a function is local: it lives only there, and the function cannot see your outside variables either
- Separate scopes prevent name clashes, so pass data in with arguments and get it back with
returninstead of reaching forglobal - A
staticlocal variable keeps its value between calls, which is perfect for a private counter
You can now:
- Predict which variables a function can and cannot see
- Move data in and out of functions cleanly, and use
staticwhen a function needs to remember
So far your code has lived in a single file. Next you will split it across files and pull them together with include and require.
Comments