Lesson 9

Learning about Scope

In this lesson you learn about the concept of scope. As you learn about user-defined functions in Lesson 10 and objects in Lesson 12, you learn the details of how scope works when you use functions and objects.

Scope refers to where a specific variable, function, or object can be seen. Scope can be local or global.

Learning about Local Variables

Think of a program as a village where the houses have blinds on all their windows. Imagine that a variable is a person taking a walk down the street. He can talk and interact with all the other people outside, but he cannot be seen by anyone inside the houses nor can he see them. If he needs to talk with someone inside a house, he has to knock on the door and be let in first.

This is the way that local scope works. Variables can be seen only where they are created. The houses are the user-defined functions you learn about in Lesson 10. If you create a variable outside a function, it cannot be seen inside the function. Conversely, if you create a variable inside a function, it can be seen only within that function.

Global scope, on the other hand, is as if that village was on a South Seas island and the houses were open-air tents. Everyone can see everyone else at all times.

Scope is local by default in PHP. Having local scope allows for encapsulation. Encapsulation means that you can create a function and know that nothing that goes on outside of that function will change anything inside the function unexpectedly. ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.