Chapter 3..PHP Basics (Part-3) |
||||
63 views
VariablesAlthough variables have been used in numerous examples in this chapter, the concept has yet to be formally introduced. This section does so, starting with a definition. Simply put, a variable is a symbol that can store different values at different times. For example, suppose you create a Web-based calculator capable of performing mathematical tasks. Of course, the user will want to plug in values of his choosing; therefore, the program must be able to dynamically store those values and perform calculations accordingly. At the same time, the programmer requires a user-friendly means for referring to these value-holders within the application. The variable accomplishes both tasks. Given the importance of this programming concept, it would be wise to explicitly lay the groundwork as to how variables are declared and manipulated. In this section, these rules are examined in detail. Variable DeclarationA variable always begins with a dollar sign, $, which is then followed by the variable name. Variable names follow the same naming rules as identifiers. That is, a variable name can begin with either a letter or an underscore and can consist of letters, underscores, numbers, or other ASCII characters ranging from 127 through 255. The following are all valid variables: Once you’ve declared your variables, you can begin assigning values to them. Two methodologies are available for variable assignment: by value and by reference. Both are introduced next. $color = "red"; $number = 12; $age = 12; $sum = 12 + "15"; // $sum = 27 Keep in mind that each of these variables possesses a copy of the expression assigned to it. For example, $number and $age each possesses their own unique copy of the value 12. If you prefer that two variables point to the same copy of a value, you need to assign by reference, introduced next. <?php $value1 = "Hello"; $value2 =& $value1; // $value1 and $value2 both equal "Hello" $value2 = "Goodbye"; // $value1 and $value2 both equal "Goodbye" ?> An alternative reference-assignment syntax is also supported, which involves appending the ampersand to the front of the variable being referenced. The following example adheres to this new syntax: <?php $value1 = "Hello"; $value2 = &$value1; // $value1 and $value2 both equal "Hello" $value2 = "Goodbye"; // $value1 and $value2 both equal "Goodbye" ?> References also play an important role in both function arguments and return values, as well as in object-oriented programming. Chapters 4 and 6 cover these Variable ScopeHowever you declare your variables (by value or by reference), you can declare them anywhere in a PHP script. The location of the declaration greatly influences the realm in which a variable can be accessed, however. This accessibility domain is known as its scope. $x = 4; function assignx () {
$x = 0; printf("\$x inside function is %d <br />", $x);
} assignx(); printf("\$x outside of function is %d <br />", $x);
Executing this listing results in the following: $x inside function is 0 $x outside of function is 4 As you can see, two different values for $x are output. This is because the $x located inside the assignx() function is local. Modifying the value of the local $x has no bearing on any values located outside of the function. On the same note, modifying the $x located outside of the function has no bearing on any variables contained in assignx(). Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be: // multiply a value by 10 and return it to the caller function x10 ($value) {
$value = $value * 10; return $value; } Keep in mind that although you can access and manipulate any function parameter in the function in which it is declared, it is destroyed when the function execution ends. You’ll learn more about functions in Chapter 4. $somevar = 15; function addit() {
GLOBAL $somevar; $somevar++; echo "Somevar is $somevar"; } addit(); The displayed value of $somevar would be 16. However, if you were to omit this line, GLOBAL $somevar; the variable $somevar would be assigned the value 1 because $somevar would then be considered local within the addit() function. This local declaration would be implicitly set to 0 and then incremented by 1 to display the value 1. $somevar = 15; function addit() {
$GLOBALS["somevar"]++; } addit(); echo "Somevar is ".$GLOBALS["somevar"]; This returns the following: Somevar is 16 Regardless of the method you choose to convert a variable to global scope, be aware that the global scope has long been a cause of grief among programmers due STATIC $somevar; Consider an example: function keep_track() {
STATIC $count = 0; $count++; echo $count; echo "<br />"; } keep_track(); keep_track(); keep_track(); What would you expect the outcome of this script to be? If the variable $count was 1 1 1 However, because $count is static, it retains its previous value each time the function 1 2 3 Static scoping is particularly useful for recursive functions. Recursive functions are a powerful programming concept in which a function repeatedly calls itself until a particular condition is met. Recursive functions are covered in detail in Chapter 4. PHP’s Superglobal VariablesPHP offers a number of useful predefined variables that are accessible from anywhere within the executing script and provide you with a substantial amount of environment- specific information. You can sift through these variables to retrieve details about the current user session, the user’s operating environment, the local operating environment, and more. PHP creates some of the variables, while the availability and value of many of the other variables are specific to the operating system and Web server. Therefore, rather than attempt to assemble a comprehensive list of all possible predefined variables and their possible values, the following code will output all predefined variables pertinent to any given Web server and the script’s execution environment: foreach ($_SERVER as $var => $value) {
echo "$var => $value <br />"; } This returns a list of variables similar to the following. Take a moment to peruse the listing produced by this code as executed on a Windows server. You’ll see some of these variables again in the examples that follow: HTTP_HOST => localhost:81 HTTP_USER_AGENT => Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.0.10) Gecko/20070216 Firefox/1.5.0.10 HTTP_ACCEPT => text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain; q=0.8,image/png,*/*;q=0.5 HTTP_ACCEPT_LANGUAGE => en-us,en;q=0.5 HTTP_ACCEPT_ENCODING => gzip,deflate HTTP_ACCEPT_CHARSET => ISO-8859-1,utf-8;q=0.7,*;q=0.7 HTTP_KEEP_ALIVE => 300 HTTP_CONNECTION => keep-alive PATH => C:\oraclexe\app\oracle\product\10.2.0\server\bin;c:\ruby\bin;C:\Windows\system32 ; C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\QuickTime\QTSystem\;c:\php52\;c:\Python24 SystemRoot => C:\Windows COMSPEC => C:\Windows\system32\cmd.exe PATHEXT => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.RB;.RBW WINDIR => C:\Windows SERVER_SIGNATURE => Apache/2.0.59 (Win32) PHP/6.0.0-dev Server at localhost Port 81 SERVER_SOFTWARE => Apache/2.0.59 (Win32) PHP/6.0.0-dev SERVER_NAME => localhost SERVER_ADDR => 127.0.0.1 SERVER_PORT => 81 REMOTE_ADDR => 127.0.0.1 DOCUMENT_ROOT => C:/apache2/htdocs SERVER_ADMIN => example@note.com SCRIPT_FILENAME => C:/apache2/htdocs/books/php-oracle/3/server.php REMOTE_PORT => 49638 GATEWAY_INTERFACE => CGI/1.1 SERVER_PROTOCOL => HTTP/1.1 REQUEST_METHOD => GET QUERY_STRING =>REQUEST_URI => /books/php-oracle/3/server.php SCRIPT_NAME => /books/php-oracle/3/server.php PHP_SELF => /books/php-oracle/3/server.php REQUEST_TIME => 1174440456 As you can see, quite a bit of information is available—some useful, some not so useful. You can display just one of these variables simply by treating it as a regular variable. For example, use this to display the user’s IP address: printf("Your IP address is: %s", $_SERVER['REMOTE_ADDR']);
This returns a numerical IP address, such as 192.0.34.166. printf("Your browser is: %s", $_SERVER['HTTP_USER_AGENT']);
This returns information similar to the following: Learning More About the Server and Client $_SERVER['HTTP_REFERER']: The URL of the page that referred the user to the current location. $_GET['cat'] = "apache" $_GET['id'] = "157" The $_GET superglobal by default is the only way that you can access variables passed via the GET method. You cannot reference GET variables like this: $cat, $id. See Chapter 21 for more about safely accessing external data. <form action="subscribe.php" method="post"> <p> Email address:<br /> <input type="text" name="email" size="20" maxlength="50" value="" /> </p> <p> Password:<br /> <input type="password" name="password" size="20" maxlength="15" value="" /> </p> <p> <input type="submit" name="subscribe" value="subscribe!" /> </p> </form> The following POST variables will be made available via the target subscribe.php script: $_POST['email'] = "example@note.com"; $_POST['pswd'] = "common"; $_POST['subscribe'] = "subscribe!"; Like $_GET, the $_POST superglobal is by default the only way to access POST variables. $_FILES['upload-name']['error']: An upload status code. Despite the name, this $_ENV['HOSTNAME']: The server hostname $_ENV['SHELL']: The system shell Retrieving Information Stored in Sessions Variable VariablesOn occasion, you may want to use a variable whose content can be treated dynamically as a variable in itself. Consider this typical variable assignment: $recipe = "spaghetti"; Interestingly, you can treat the value spaghetti as a variable by placing a second dollar sign in front of the original variable name and again assigning another value: $$recipe = "& meatballs"; This in effect assigns & meatballs to a variable named spaghetti. echo $recipe $spaghetti; echo $recipe ${$recipe};
The result of both is the string spaghetti & meatballs. |
| « C# Day 2 - Objects and Types (part 2) | C# Day 2 - Objects and Types (part 3) » |
| Posted on Monday, February 9th, 2009 at 4:22 pm under PHP and MySQL - From Beginning to Professional | RSS 2.0 Feed | |
February 9th, 2009 at 5:47 pm
[...] Chapter 3..PHP Basics(Part-3) (Variables,Variable Declaration,Variable Scope,PHP’s Superglobal Variables,Variable Variables) [...]