- Before You Begin: Accessing PHP
- Creating a Sample Application: Bob's Auto Parts
- Embedding PHP in HTML
- Adding Dynamic Content
- Accessing Form Variables
- Understanding Identifiers
- Examining Variable Types
- Declaring and Using Constants
- Understanding Variable Scope
- Using Operators
- Working Out the Form Totals
- Understanding Precedence and Associativity
- Using Variable Handling Functions
- Making Decisions with Conditionals
- Repeating Actions Through Iteration
- Breaking Out of a Control Structure or Script
- Employing Alternative Control Structure Syntax
- Using declare
- Next
Understanding Variable Scope
The term scope refers to the places within a script where a particular variable is visible. The six basic scope rules in PHP are as follows:
Built-in superglobal variables are visible everywhere within a script.
Constants, once declared, are always visible globally; that is, they can be used inside and outside functions.
Global variables declared in a script are visible throughout that script, but not inside functions.
Variables inside functions that are declared as global refer to the global variables of the same name.
Variables created inside functions and declared as static are invisible from outside the function but keep their value between one execution of the function and the next. (We explain this idea fully in Chapter 5.)
Variables created inside functions are local to the function and cease to exist when the function terminates.
The arrays $_GET and $_POST and some other special variables have their own scope rules. They are known as superglobals and can be seen everywhere, both inside and outside functions.
The complete list of superglobals is as follows:
$GLOBALS—An array of all global variables (Like the global keyword, this allows you to access global variables inside a function—for example, as $GLOBALS['myvariable'].)
$_SERVER—An array of server environment variables
$_GET—An array of variables passed to the script via the GET method
$_POST—An array of variables passed to the script via the POST method
$_COOKIE—An array of cookie variables
$_FILES—An array of variables related to file uploads
$_ENV—An array of environment variables
$_REQUEST—An array of all user input including the contents of input including $_GET, $_POST, and $_COOKIE (but not including $_FILES)
$_SESSION—An array of session variables
We come back to each of these superglobals throughout the book as they become relevant.
We cover scope in more detail when we discuss functions and classes later in this chapter. For the time being, all the variables we use are global by default.