Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 86 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
86
Dung lượng
1,1 MB
Nội dung
To create this JavaScript code dynamically through PHP, we must be careful to escape the backslashes in PHP so that they are passed literally to the JavaScript. For example, consider what happens if we leave the backslashes unescaped: <HTML> <BODY> <SCRIPT LANGUAGE='javascript'> <?php $applicant="Chris"; echo ("alert (\"Welcome!\n\n\tApplicant: $applicant\");"); // Wrong! ?> </SCRIPT> </BODY> </HTML> This is what we would see if we "View Source" in the browser: The newlines and tabs were interpreted by PHP instead of being passed as literal characters to JavaScript. This was not our intended effect. We want JavaScript to interpret these symbols as newlines and tabs, not PHP. The code below corrects this problem: <SCRIPT LANGUAGE='javascript'> <?php echo ("alert (\"Welcome!\\n\\n\\tApplicant: $applicant\");"); ?> </SCRIPT> Basically, we escape the \n by typing \\n. PHP will not interpret it as a newline, but rather as the literal characters \ and n. These will be passed on to the browser, where JavaScript will then interpret them as a newline. Similarly, the PHP code \\t causes \t to be passed to the browser, which is correctly interpreted as a tab by JavaScript. Summary In the chapter, we learned how PHP interacts with the browser, how it receives HTML form data, and how it dynamically generates HTML documents. Upon submission, HTML form data are converted to name/value pairs and sent to the web server in a URL-encoded query string. URL encoding ensures that reserved characters are safely masked and that name/value pairs are represented in a standard way. PHP receives the data in the form of variables. URL encoding can also be used to pass variables from one PHP script to another. PHP provides three notations for comments: ❑ // Comment ❑ # Comment ❑ /* Comment */ The first two of the comment types are used to comment single lines. The third type of comment code can be used to comment blocks of multiple lines. The backslash (\) is used to escape a character. Characters are often escaped to indicate a literal depiction of the character: echo ("The variable \$applicant equals $applicant."); Some escape sequences have special meanings, such as \n (newline) and \t (tab). 4 Variables, Constants 1 , and Data Types In the previous chapter, we met PHP variables and saw briefly how to use them. We stated that PHP variables must begin with the dollar character ($) and that PHP is a weakly-typed language – that is, variables can contain any type of data and do not have to be predefined as strings, integers, etc. We also saw how we can use PHP variables to extract data from an HTML form. In this chapter, we will look in more detail at variables and their data types. We will consider the issue of data type juggling in more detail, and we will look at some of the functions we can use to manipulate variables. We will also see how to assign a name to a constant value, which remains the same throughout the program. Data Types PHP has three basic data types: integer, double and string. There are also some not-so-basic types, namely arrays and objects, which are discussed in later chapters. Every variable has a specific type, though, as we’ve already mentioned, a variable’s type may change on the fly as the variable’s value changes, or as the code otherwise dictates. Integers use four bytes of memory and are used to represent ordinary, non-decimal numbers in the range of approximately –2 billion to +2 billion. Doubles, also known as float (floating-point) or real numbers, are used to represent numbers that contain a decimal value or an exponent. Strings are used to represent non- numeric values, like letters, punctuation marks, and even numerals. 2 // This is an integer 1 [JHS] I've added a bit of an introduction to avoid the abrupt start to the chapter. The chapter seems technically accurate, but I think we could do with a bit more explantion in places. The major topic which is omitted from this chapter is HTTP environment variables. We need a large section on these. While a complete listing should form an appendix, we need to show in this chapter how to access HTTP variables from PHP and to give a couple of practical examples: it would be good if these could be incorporated into the Job Application Form. 2.0 // This is a double "2" // This is a string "2 hours" // This is another string Many languages contain a Boolean data type to represent the logical values TRUE and FALSE. PHP does not. It instead uses expressions of the other three basic types that evaluate to either true or false values. Among integers, 0 (zero) evaluates as a false value, and any non-zero integer evaluates as a true value. Similarly, the double value 0.0 (or equivalents, such as 0.000) evaluates to FALSE, and any non-zero value evaluates to TRUE. Among strings, the empty string evaluates to FALSE. It is represented as a pair of quotation marks containing nothing: "". Any non-empty string evaluates to TRUE. Literals and Identifiers Variables, constants, functions and classes must have distinct labels in order to be useful. Within these labels there is a distinction between literals and names. Literals are raw data, what you see is what you get. You can have number literals (e.g. 786) or string literals (e.g. "a quoted string"). Basically, you cannot make a literal mean something other than what it literally means. Names, on the other hand, acquire their meaning by convention or by decree. The connection between a name and its meaning is arbitrary, a rose, as you know, "by any other name would smell as sweet". Names used in programming are called identifiers. Identifiers in PHP are case-sensitive, so $price and $Price are different variables. Built-in functions and structures are not case-sensitive, however; so echo and ECHO do the same thing. Identifiers may consist of any number of letters, digits, underscores, or dollar signs but cannot begin with a digit. Data Values In addition to its meaning in the program, an identifier also has a value, which is a data item of a specific data type. If the identifier is able to change its value through the course of the program it is called a variable, whereas if the identifier has a fixed value, it is known as a constant. Constants Constants are values that never change. Common real-life constants include the value of pi (approx. 3.14), the freezing point of water under normal atmospheric pressure (0° C), and the value of "noon" (12:00). In terms of programming, there are two types of constants: literal and symbolic constants. Literal constants are simply unchanging values that are referred to directly, without using an identifier. When we use the term “constants”, we normally are referring to symbolic constants. Symbolic constants are a convenient way to assign a value once to an identifier and then refer to it by that identifier throughout your program. For example, the name of your company is a rather constant value. Rather than include the literal string "Phop's Bicycles" all throughout your application, you can define a constant called COMPANY with the value "Phop's Bicycles" and use this to refer to the company name throughout your code. Then, if the name ever does change as a result of a merger or a marketing ploy, there is only one place where you need to update your code: the point at which you defined the constant. Notice that constant names, unlike variable names, do not begin with a dollar sign. Defining Constants The define() function is used to create constants: define("COMPANY", "Phop's Bicycles"); define("YELLOW", "#FFFF00"); define("VERSION", 3); define("NL", "<BR>\n"); In the last example, we define a constant called NL that represents an HTML break tag followed by a newline character. Essentially, we have created a coding shortcut, since “ <BR>\n” is a commonly used combination. By convention, programmers define constants using all capital letters. A constant may contain any number or string value. Once constants are defined, they can be used in lieu of their values: echo("Employment at " . COMPANY . NL); This is equivalent to: echo("Employment at Phop's Bicycles<BR>\n"); Notice that the constant appears outside of the quotation marks. The line: echo("Employment at COMPANY NL"); Would literally print "Employment at COMPANY NL" to the browser. defined() The defined() function allows you to determine whether or not a constant exists. It returns 1 if the constant exists and 0 if it does not: if (defined("YELLOW")) { echo ("<BODY BGCOLOR=" . YELLOW . ">\n"); } Built-in Constants PHP includes several built-in constants. TRUE and FALSE are pre-defined with respective true (1) and false (0 or empty string) values. The constant PHP_VERSION indicates the version of the PHP parser that is currently running, such as 3.0.11. The constant PHP_OS indicates the server-side operating system on which the parser is running. echo(PHP_OS); // Prints "Linux" (for example) __FILE__ and __LINE__ hold the name of the script that is being parsed and the current line number within the script. (There are two underscore characters before and after the names of these constants.) PHP also includes a number of constants for error reporting: E_ERROR, E_WARNING, E_PARSE, and E_NOTICE. Furthermore, PHP utilizes a number of predefined variables that provide information about the environment on which PHP is running. A full list is included in Appendix ?. In order to view what these variables are set to on your computer, you can use the function phpinfo() as shown in the following code: <HTML> <! phpinfo.php > <BODY> <?php phpinfo() ?> </BODY> </HTML> This should produce the page shown in the screenshot below: Variable Declaration and Initialization Different to constants, a variable is automatically declared in PHP when you assign a value to it. Assignment is accomplished with the assignment operator (=). Note that the assignment operator (=) and the equality operator (==) are different in PHP, as we shall see in the next chapter. $num rows = 10; $product = "Tire Pump"; $price = 22.00; $shipping = 5.00; $total = $price + $shipping; Type Juggling and Type Casting As mentioned previously, every PHP variable has a data type. That type is determined automatically by the value that is assigned to the variable. $a = 1; // $a is an integer $a = 1.2; // Now it's a double $a = "A"; // Now it's a string As we’ll learn in the next few sections, there are also ways to explicitly specify the type of a variable. String Conversion and Type Juggling If you perform a numerical operation on a string, PHP will evaluate the string as a number. This is known as string conversion, although the variable containing the string itself may not necessarily change. In the following example, $str is assigned a string value: $str = "222B Baker Street"; If we attempt to add the integer value 3 to $str, $str will be evaluated as the integer 222 for purposes of the calculation: $x = 3 + $str; // $x = 225; But the $str variable itself has not changed: echo ($str); // Prints: "222B Baker Street" String conversion follows a couple of rules: ❑ Only the beginning of the string is evaluated as a number. If the string begins with a valid numerical value, the string will evaluate as that value; otherwise it will evaluate as zero. The string "3rd degree" would evaluate as 3 if used in a numerical operation, but the string "Catch 22" would evaluate as 0 (zero). ❑ A string will be evaluated as a double only if the double value being represented comprises the entire string. The strings "3.4", "-4.01", and "4.2e6" would evaluate as the doubles 3.4, -4.01, and 4.2000000. However if other non-double characters are included in the string, the string will evaluate as an integer: "3.4 children" would evaluate as the integer 3. The string "-4.01 degrees" would evaluate as the integer -4. In addition to string conversion, PHP performs type juggling between the two numeric types. If you perform a numerical operation between a double and an integer, the result will be a double: $a = 1; // $a is an integer $b = 1.0; // $b is a double $c = $a + $b; // $c is a double (value 2.0) $d = $c + "6th"; // $d is a doube (value 8.0) Type Casting Type casting allows you to explicitly change the data type of a variable: $a = 11.2; // $a is a double $a = (int) $a // Now it's an integer (value 11) $a = (double) $a // Now it's a double again (value 11.0) $b = (string) $a // $b is a string (value "11") (array) and (object) casts are also allowed. (integer) is a synonym for (int). (float) and (real) are synonyms for (double). Variable Variables PHP supports variable variables. Ordinary variables have dynamic values: you can set and change the variable's value. With variable variables, the name of the variable is dynamic. Variable variables generally create more confusion than convenience (especially when used with arrays). They are included here for the sake of completeness; but in practice, they are of little real benefit. Here is an example of a variable variable: $field = "ProductID"; $$field = "432BB"; The first line of the code above creates a string variable called $field and assigns it the value "ProductID". The second line then uses the value of the first variable to create the name of the second variable. The second variable is named $ProductID and has the value "432BB". The following two lines of code produce the same output: echo ($ProductID); // Prints: 432BB echo ($$field); // Prints: 432BB Useful Functions for Variables PHP has a number of built-in functions for working with variables. gettype() gettype() determines the data type of a variable. It returns one of the following values: ❑ "integer" ❑ "double" ❑ "string" ❑ "array" ❑ "object" ❑ "class" ❑ "unknown type" We shall see more on arrays, objects and classes in later chapters. An example using gettype() may be: if (gettype ($user_input) == "integer") { $age = $user_input; } Related functions: isset(), settype() settype() The settype() function explicitly sets the type of a variable. The type is written as a string and may be one of the following: array, double, integer, object or string. If the type could not be set then a false value is returned. $a = 7.5; // $a is a double settype($a, "integer"); // Now it's an integer (value 7) settype() returns a true value if the conversion is successful. Otherwise it returns false. if (settype($a, "array")) { echo("Conversion succeeded."); } else { echo ("Conversion error."); } isset() and unset() unset() is used to destroy a variable, freeing all the memory that is associated with the variable so it is then available again. The isset() function is used to determine whether a variable has been given a value. If a value has been set then it returns true. $ProductID = "432BB"; if (isset($ProductID)) { echo("This will print"); } unset($ProductID); if (isset ($ProductID)) { echo("This will NOT print"); } Related functions: empty() empty() empty() is nearly the opposite 2 of isset(). It returns true if the variable is not set, or has a value of zero or an empty string. Otherwise it returns false. echo empty($new); // true $new = 1; echo empty($new); // false $new = ""; echo empty($new); // true $new = 0; echo empty($new); // true $new = "Buon giorno"; echo empty($new); // false unset ($new); echo empty($new); // true The is () functions The functions is_int(), is_integer(), and is_long() are all synonymous functions that determine whether a variable is an integer. is_double(), is_float(), and is_real() determine whether a variable is a double. is_string(), is_array(), and is_object() work similarly for their respective data types. $ProductID = "432BB"; if (is string ($ProductID)) { echo ("String"); } The val() functions PHP provides yet another way to explicitly set the data type of a variable: the intval(), doubleval(), and strval() functions. These functions cannot be used to convert arrays or objects. $ProductID = "432BB"; $i = intval($ProductID); // $i = 432; The intval() function can take an optional second argument representing the base to use for the conversion. By default, the function uses base 10 (decimal numbers). In the example below, we specify base 16 (hexadecimal numbers): 2 [kk] Empty() is NOT the opposite of isset() and this is important do know. Unlike Perl, PHP3 internally does not signal “undef” (undefined value) and “”/0 (zero value) in a different way and isset() is really the only way to determine this difference. That is why next(), prev() and the like are broken. [...]... Subtraction 7 - 2 Calculates the difference when 2 is subtracted from 7: 5 * Multiplication 7 * 2 Calculates the product of 7 and 2: 14 / Division 7 / 2 Calculates the dividend when 7 is divided by 2: 3.5 % Modulus 7 % 2 Calculates the remainder when 7 is divided by 2: 1 PHP generally ignores space characters Although $x = 6 * 2; and $x=6 *2; are equally legal in PHP, the former is far more readable, and therefore... 6 + 2, 6 and 2 are the operands, and the expression evaluates to 8 Operators in PHP are mostly similar to those in C, Perl and related languages This chapter describes them in detail Arithmetic Operators Like every programming language, PHP uses the basic mathematical operators: Operator Operation Performed Example Description + Addition 7 + 2 Calculates the sum of 7 and 2: 9 - Subtraction 7 - 2 Calculates... HTML form dynamic by including PHP scripts in it This means that we have to rename the file from "jobapp.html" to "jobapp .php" Otherwise, PHP scripts will not be parsed by the web server Once we have renamed the file, we can add our PHP tags that define and use the needed constant: .php > < ?php define ("COMPANY", "Phop's Bicycles"); ?> < ?php echo (COMPANY); ?> Job Application...$ProductID = "432BB"; $i = intval ($ProductID, 16); // $i = (decimal )27 5131 ; "432BB" was interpreted as a five-digit hexadecimal number Building an Online Job Application Form The sample application begun in the previous chapter illustrates how PHP variables are automatically created when HTML form data are submitted to a PHP script Let's introduce a few more variables... ^= $i $h = $h ^ $i $h = $i $h = $h $i $h >>= 2 $h = $h >> 2 $h . " ;22 2B Baker Street"; If we attempt to add the integer value 3 to $str, $str will be evaluated as the integer 22 2 for purposes of the calculation: $x = 3 + $str; // $x = 22 5; . divided by 2: 3.5 % Modulus 7 % 2 Calculates the remainder when 7 is divided by 2: 1 PHP generally ignores space characters. Although $x = 6 * 2; and $x=6 *2; are equally legal in PHP, . - Subtraction 7 - 2 Calculates the difference when 2 is subtracted from 7: 5 * Multiplication 7 * 2 Calculates the product of 7 and 2: 14 / Division 7 / 2 Calculates the dividend