PHP variable scope

PHP variable scope: If you have a very long program, it’s quite possible that you could start to run out of good variable names, but with PHP you can decide the scope of a variable. In other words, you can, for example, tell it that you want the variable $temp to be used only inside a particular function and to forget it was ever used when the function returns. In fact, this is the default scope for PHP variables.
Alternatively, you could inform PHP that a variable is global in scope and thus can be accessed by every other part of your program.

Local variables

Local variables are variables that are created within, and can only be accessed by, a function. They are generally temporary variables that are used to store partially processed results prior to the function’s return.
One set of local variables is the list of arguments to a function. In the previous section, we defined a function that accepted a parameter named $timestamp. This is meaningful only in the body of the function; you can’t get or set its value outside the function.
For another example of a local variable, take another look at the longdate function, which is modified slightly in Example 3-13.

Example 3-13. An expanded version of the longdate function
<?php
 function longdate($timestamp)
 {
 $temp = date("l F jS Y", $timestamp);
 return "The date is $temp";
 }
?>

Here we have assigned the value returned by the date function to the temporary variable $temp, which is then inserted into the string returned by the function. As soon as the function returns, the value of $temp is cleared, as if it had never been used at all. Now, to see the effects of variable scope, let’s look at some similar code in

Example 3-14. Here $temp has been created before we call the longdate function.
Example 3-14. This attempt to access $temp in function longdate will fail
<?php
$temp = "The date is ";
echo longdate(time());
function longdate($timestamp)
{
return $temp . date("l F jS Y", $timestamp);
}
?>

However, because the $temp was neither created within the longdate function nor passed to it as a parameter, longdate cannot access it. Therefore, this code snippet outputs only the date, not the preceding text. In fact, it will first display the error message Notice: Undefined variable: temp. The reason for this is that, by default, variables created within a function are local to
that function and variables created outside of any functions can be accessed only by
non-function code.
Some ways to repair Example 3-14 appear in Examples 3-15 and 3-16.

Example 3-15. Rewriting to refer to $temp within its local scope fixes the problem
<?php
$temp = "The date is ";
echo $temp . longdate(time());
function longdate($timestamp)
{
return date("l F jS Y", $timestamp);
}
?>

 

 

Example 3-15 moves the reference to $temp out of the function. The reference appears
in the same scope where the variable was defined.
The solution in Example 3-16 passes $temp to the longdate function as an extra argu‐
ment. longdate reads it into a temporary variable that it creates called $text and outputs
the desired result.
Example 3-16. An alternative solution: passing $temp as an argument

<?php
$temp = "The date is ";
echo longdate($temp, time());
function longdate($text, $timestamp)
{
return $text . date("l F jS Y", $timestamp);
}
?>

 

Forgetting the variable scope is a common programming error,
so remembering how variable scope works will help you debug some
quite obscure problems. Suffice it to say that unless you have declared a variable otherwise, its scope is limited to being local: either
to the current function, or to the code outside of any functions, de‐
pending on whether it was first created or accessed inside or out‐
side a function.

 

Global variables

There are cases when you need a variable to have a global scope because you want all your code to be able to access it. Also, some data may be large and complex, and you don’t want to keep passing it as arguments to functions.
To declare a variable as having global scope, use the keyword global. Let’s assume that you have a way of logging your users into your website and want all your code to know whether it is interacting with a logged-in user or a guest. One way to do this is to create a global variable such as $is_logged_in:

global $is_logged_in;

 

Now your login function simply has to set that variable to 1 upon a successful login attempt, or 0 upon its failure. Because the scope of the variable is global, every line of code in your program can access it.
You should use global variables with caution, though. I recommend that you create them only when you absolutely cannot find another way of achieving the result you desire.

In general, programs that are broken into small parts and segregated data are less buggy and easier to maintain. If you have a thousand-line program (and someday you will) in which you discover that a global variable has the wrong value at some point, how long will it take you to find the code that set it incorrectly?
Also, if you have too many global variables, you run the risk of using one of those names again locally, or at least thinking you have used it locally, when in fact it has already  been declared as global. All manner of strange bugs can arise from such situations.

SometimesI adopt the convention of making all global variable names uppercase (just as it’s recommended that constants should be upper‐case)  so that I can see at a glance the scope of a variable

Static variables

In the section “Local variables” on page 66, I mentioned that the value of the variable is wiped out when the function ends. If a function runs many times, it starts with a fresh copy of the variable and the previous setting has no effect.
Here’s an interesting case. What if you have a local variable inside a function that you don’t want any other parts of your code to have access to, but you would also like to keep its value for the next time the function is called? Why? Perhaps because you want a counter to track how many times a function is called. The solution is to declare a static variable, as shown in Example 3-17.

Example 3-17. A function using a static variable
<?php
function test()
{
static $count = 0;
echo $count;
$count++;
}
?>

Here the very first line of function test creates a static variable called $count and initializes it to a value of 0. The next line outputs the variable’s value; the final one increments it.
The next time the function is called because $count has already been declared, the first line of the function is skipped. Then the previously incremented value of $count is displayed before the variable is again incremented.
If you plan to use static variables, you should note that you cannot assign the result of an expression in their definitions. They can be initialized only with predetermined values (see Example 3-18).

Example 3-18. Allowed and disallowed static variable declarations
<?php
 static $int = 0; // Allowed
 static $int = 1+2; // Disallowed (will produce a Parse error)
 static $int = sqrt(144); // Disallowed
?>

Superglobal variables

Starting with PHP 4.1.0, several predefined variables are available. These are known as superglobal variables, which means that they are provided by the PHP environment but are global within the program, accessible absolutely everywhere. These superglobals contain lots of useful information about the currently running program and its environment (see Table 3-6). They are structured as associative arrays, a topic discussed in Chapter 6.

Table 3-6. PHP’s superglobal variables

 

Superglobal Name Content
$GLOBALS All variables that are currently defined in the global scope of the script. the variable names are the keys of the array.
$_SERVER Information such as headers, paths, and script locations. the entries in this array are created by the web server, and there is no guarantee that every web server will provide any or all of these.
$_GET Variables passed to the current script via the HTTP GET method.
$_POST Variables passed to the current script via the HTTP POST method.
$_FILES Items uploaded to the current script via the HTTP POST method.
$_COOKIE Variables passed to the current script via HTTP cookies.
$_SESSION Session variables available to the current script.
$_REQUEST Contents of information passed from the browser; by default, $_GET, $_POST, and $_COOKIE.
$_ENV Variables passed to the current script via the environment method.

All of the superglobals (except for $GLOBALS) are named with a single initial underscore and only capital letters; therefore, you should avoid naming your own variables in this a manner to avoid potential confusion.
To illustrate how you use them, let’s look at a bit of information that many sites employ.
Among the many nuggets of information supplied by superglobal variables is the URL of the page that referred the user to the current web page. This referring page information can be accessed like this:

$came_from = $_SERVER['HTTP_REFERER'];

It’s that simple. Oh, and if the user came straight to your web page, such as by typing its URL directly into a browser, $came_from will be set to an empty string.

 

Superglobals and security

A word of caution is in order before you start using superglobal variables because they are often used by hackers trying to find exploits to break into your website. What they do is load up $_POST, $_GET, or other superglobals with malicious code, such as Unix or MySQL commands that can damage or display sensitive data if you naïvely access them.
Therefore, you should always sanitize superglobals before using them. One way to do this is via the PHP htmlentities function. It converts all characters into HTML entities.
For example, less-than and greater-than characters (< and >) are transformed into the strings &lt; and &gt; so that they are rendered harmless, as are all quotes and backslashes, and so on.
Therefore, a much better way to access $_SERVER (and other superglobals) is:

 

$came_from = htmlentities($_SERVER['HTTP_REFERER']);

Using the htmlentities function for sanitization is an important practice in any circumstance where user or other third-party data is being processed for output, not just with superglobals.

 

This Tutorial has provided you with a solid background in using PHP. In next Tutorials, we’ll start using what you’ve learned to build expressions and control program flow—in other words, do some actual programming.

<< Prev Next >>

Loading