Variables and Constants


In the previous chapter, we were introduced to variables in PHP. So far, we have seen basic examples of their use throughout the code snippets. Now, we will turn our attention to constants, an equally useful feature, and discuss variable usage in more detail.

Defining Constants

Constants are a way of associating a scalar value with a string token to aid code maintenance and readability. You define constants in your PHP applications by using the define language construct, which takes a string for the constant's name along with a scalar value and creates that constant. Constant names have the same rules as variable names, although they do not begin with a $ character, and their values can only be of certain types: integer, float, string, or Boolean.

You use constants by simply referring to their name.

 <?php   define('NORMAL_USER', 0);   define('ADMIN_USER', -1);   define('GUEST_USER', 1);   define('GUEST_ACCT_NAME', "Guest User");   define('GUEST_CAN_LOGIN', FALSE);   //   // default to guest permissions.   //   $user_name = GUEST_USER_NAME;   $user_can_login = GUEST_CAN_LOGIN; ?> 

Once a constant is defined, it can never be changed within an executing script. Attempting to define the constant name again generates a warning and ignores the new value. To see if a constant has been defined or not, use the defined function provided by PHP, which returns a Boolean value.

By Value and by Reference Variables

By default, most variables and all constants are assigned by value. When you assign a value from one variable to another, the value is copied. This works for all types except objects.

 <?php   $a = 123;   $b = $a;              // $b now has a copy of the value 123   $c = "happy";   $d = $c;              // $d now contains a copy of "happy"   $e = array(1, 2, 3);   $f = $e;              // both $e and $f have (1, 2, 3)   $f[2] = 4;            // $f now has (1, 2, 4), $e unchanged!   $g = NORMAL_USER;     // $g now has value of constant                         //   NORMAL_USER (0) ?> 

This behavior can be extremely confusing to programmers who are not used to arrays being copied by value:

 <?php   $arr = array(array(1), array(2), array(3));   $sub = $arr[0];   $sub[0] = 100;   echo $sub[0];   echo $arr[0][0]; ?> 

The previous script prints 100 and 1 because the entire array is copied when the array is assigned to the $sub variable.

For object variables and resources, all that is copied over is the handle to the underlying object or resource, so even though the variable is copied by value, the underlying object on which all operations take place remains the same.

Another option for assigning values to variables from variables is to assign by reference. With this, you can tell a variable to act as a sort of "alias" to another variable, with both referring to the same data. This is done by prefixing a variable with the & operator.

 <?php   $a = 123;   $b = &$a;          // $b and $a now refer to the SAME thing.   $a = 456;          // $b now also has the value 456 !   $arr = array(array(1), array(2), array(3));   $sub = &$arr[0];   // $sub refers to SAME array as $arr[0]   $sub[0] = 100;     // $sub[0] and $arr[0][0] are now BOTH 100 ?> 

As for constants, you can never assign a value to one once it is defined, nor can you refer to a constant by reference. Programmers are encouraged to be careful when using by-reference variables since they can negatively affect the readability and maintainability of the code.

Variable Scope

Like most languages, PHP has clearly defined rules where the use of a variable is considered valid. This is known as variable scope. PHP has three different scoping schemes:

  • Function-level variables Variables that you declare within a function that are valid only within that function. We will learn more about these in Chapter 3, "Code Organization and Reuse."

  • Variables declared within "regular" script (global variables) Variables that you declare and use within a script outside of any functions that are only valid at that level and invisible from within functions by default. However, there is a mechanism by which you can make them visible from within functions, which we will cover in Chapter 3.

  • "Superglobal" variables A certain number of variables that are simply available everywhere, and can be accessed anywhere in your scripts. Currently, users cannot define their own superglobal variables. We will point these out as we encounter them throughout this book.

Furthermore, variables declared in one section or one snippet of PHP code within a script file are visible to the other snippets of code that come after it in the same script execution.

 <?php   $variable = "Hello There!"; ?>   <p align='center'>     I have a message for you:   </p>   <p align='center'> <?php   echo $variable;                 // prints "Hello There!" ?>   </p> 

Constants are valid anywhere within your scripts and have no scoping limitations.

Variable Lifetime

One of the most confusing aspects of PHP concerns the lifetime of variables and other data in the language; in other words, "how long they last."

Variables are declared and retain their values during the execution of the current script and any other scripts it immediately uses. When script execution ends, the variables and their values are lost. For each PHP script you execute in a web browser, you have to re-declare any variables you wish to use and re-assign any values. Whether you execute the same script or a different one, PHP remembers nothing between invocations.

The language does not provide by default any means of remembering values between individually executing scripts. In later chapters, we shall see some features that allow us to store data for specific users between requests. Apart from that, though, we must assume a "clean slate" each time our scripts start.

Predefined Variables

PHP comes with a number of predefined variables that give us information about our current operating environment: Most are superglobal arrays, with key names referring to specific information to be queried. We will give you a quick overview of these now (see Chapter 7, "Interacting with the Server: Forms," for more information on predefined variables.)

  • $GLOBALS This contains a reference to all of the variables that are available globally within the executing script. The keys of the array are the names of the variables.

  • $_SERVER This contains information about the context in which the script is executing, such as the name of the server, the name of the page being run, information about the connection, and so on.

  • $_GET, $_POST These contain variables that a page might send to the server as part of an HTML <form> element.

  • $_SESSION, $_COOKIE These contain information about managing visitors and about a storage facility known as "cookies." We will cover this in more detail in Chapter 19, "Cookies and Sessions."

  • $_REQUEST This contains the content of the $_POST, $_GET, and $_SESSION arrays.

  • $_ENV This contains the environment variables for the process in which the PHP language engine is executing. The keys of the array are the names of environment variables.

  • $php_errormsg This holds the last error message that was generated by the PHP language engine while executing the current script. It is only available within the scope of the code where the error occurred, and if the TRack_errors configuration option in php.ini is turned on. (By default, it is not.)

We will see and use many of these predefined values as we work our way through the various topics involved in writing web applications.




Core Web Application Development With PHP And MYSQL
Core Web Application Development with PHP and MySQL
ISBN: 0131867164
EAN: 2147483647
Year: 2005
Pages: 255

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net