SAMS Teach Yourself PHP4 in 24 Hours phần 2 pps

45 275 0
  • Loading ...
1/45 trang

Thông tin tài liệu

Ngày đăng: 06/08/2014, 09:20

46 Figure 3.5: The output of Listing 3.2 as HTML source code. Adding Comments to PHP Code Code that seems clear at the time of writing, can seem like a hopeless tangle when you come to amend it six months later. Adding comments to your code as you write can save you time later on and make it easier for other programmers to work with your code. NEW TERM A comment is text in a script that is ignored by the interpreter. Comments can be used to make code more readable, or to annotate a script. Single line comments begin with two forward slashes ( / /) or a single hash sign (#). All text from either of these marks until either the end of the line or the PHP close tag is ignored. // this is a comment # this is another comment Multiline comments begin with a forward slash followed by an asterisk (/ * ) and end with an asterisk followed by a forward slash ( * /). / * this is a comment none of this will be parsed by the interpreter * / 47 Summary You should now have the tools at your disposal to run a simple PHP script on a properly configured server. In this hour, you created your first PHP script. You learned how to use a text editor to create and name a PHP document. You examined four sets of tags that you can use to begin and end blocks of PHP code. You learned how to use the print() function to send data to the browser, and you brought HTML and PHP together into the same script. Finally, you learned about comments and how to add them to PHP documents. Q&A Q Which are the best start and end tags to use? A It is largely a matter of preference. For the sake of portability the standard tags (<?php ?>) are probably the safest bet. Short tags are enabled by default and have the virtue of brevity. Q What editors should I avoid when creating PHP code? A Do not use word processors that format text for printing (such as Word, for example). Even if you save files created using this type of editor in plain text format, hidden characters are likely to creep into your code. Q When should I comment my code? A This is a matter of preference once again. Some short scripts will be self-explanatory to you, even after a long interval. For scripts of any length or complexity, you should comment your code. This often saves you time and frustration in the long run. Workshop The Workshop provides quiz questions to help you solidify your understanding of the material covered. Try to understand the quiz answers before continuing to the next hour's lesson. Quiz answers are provided in Appendix A. 48 Quiz Can a user read the source code of PHP script you have successfully installed? What do the standard PHP delimiter tags look like? What do the ASP PHP delimiter tags look like? What do the script PHP delimiter tags look like? What function would you use to output a string to the browser? Activity Familiarize yourself with the process of creating, uploading, and running PHP scripts. 49 Hour 4: The Building Blocks Overview In this hour, you are going to get your hands dirty with some of the nuts and bolts of the language. There's a lot of ground to cover, and if you are new to programming, you might feel bombarded with information. Don't worry— you can always refer back here later on. Concentrate on understanding rather than memorizing the features covered. If you're already an experienced programmer, you should at least skim this hour's lesson. It covers a few PHP-specific features. In this hour, you will learn About variables— what they are and how to use them How to define and access variables About data types About some of the more commonly used operators How to use operators to create expressions How to define and use constants Variables A variable is a special container that you can define to "hold" a value. A variable consists of a name that you can choose, preceded by a dollar ($) sign. The variable name can include letters, numbers, and the underscore character (_). Variable names cannot include spaces or characters that are not alphanumeric. The following code defines some legal variables: $a; $a_longish_variable_name; $2453; $sleepyZZZZ Remember that a semicolon (;) is used to end a PHP statement. The semicolons in the previous fragment of code are not part of the variable names. NEW TERM A variable is a holder for a type of data. It can hold numbers, strings of characters, objects, arrays, or booleans. The contents of a variable can be changed at any time. 50 As you can see, you have plenty of choices about naming, although it is unusual to see a variable name that consists exclusively of numbers. To declare a variable, you need only to include it in your script. You usually declare a variable and assign a value to it in the same statement. $num1 = 8; $num2 = 23; The preceding lines declare two variables, using the assignment operator (=) to give them values. You will learn about assignment in more detail in the Operators and Expressions section later in the hour. After you give your variables values, you can treat them exactly as if they were the values themselves. In other words print $num1; is equivalent to print 8; as long as $num1 contains 8. Dynamic Variables As you know, you create a variable with a dollar sign followed by a variable name. Unusually, the variable name can itself be stored in a variable. So, when assigning a value to a variable $user = "bob"; is equivalent to $holder="user"; $$holder = "bob"; The $holder variable contains the string "user", so you can think of $$holder as a dollar sign followed by the value of $holder. PHP interprets this as $user. Note You can use a string constant to define a dynamic variable instead of a variable. To do so, you must wrap the string you want to use for the variable name in braces: ${"user"} = "bob"; This might not seem useful at first glance. However, by using the concatenation operator and a loop (see Hour 5, "Go ing with the Flow"), you can use this technique to create tens of variables dynamically. When accessing a dynamic variable, the syntax is exactly the same: $user ="bob"; print $user; is equivalent to $user ="bob"; $holder="user"; 51 print $$holder; If you want to print a dynamic variable within a string, however, you need to give the interpreter some help. The following print statement: $user="bob"; $holder="user"; print "$$holder"; does not print "bob" to the browser as you might expect. Instead it prints the strings "$" and "user" together to make "$user". When you place a variable within quotation marks, PHP helpfully inserts its value. In this case, PHP replaces $holder with the string "user". The first dollar sign is left in place. To make it clear to PHP that a variable within a string is part of a dynamic variable, you must wrap it in braces. The print statement in the following fragment: $user="bob"; $holder="user"; print "${$holder}"; now prints "bob", which is the value contained in $user. Listing 4.1 brings some of the previous code fragments together into a single script using a string stored in a variable to initialize and access a variable called $user. Listing 4.1: Dynamically Setting and Accessing Variables 1: <html> 2: <head> 3: <title>Listing 4.1 Dynamically setting and accessing variables</title> 4: </head> 5: <body> 6: <?php 7: $holder = "user"; 8: $$holder = "bob"; 9: 10: // could have been: 11: // $user = "bob"; 12: // ${"user"} = "bob"; 13: 14: print "$user<br>"; // prints "bob" 15: print $$holder; // prints "bob" 16: print "<br>"; 17: print "${$holder}<br>"; // prints "bob" 18: print "${'user'}<br>"; // prints "bob" 19: ?> 52 20: </body> 21: </html> References to Variables By default, variables are assigned by value. In other words, if you were to assign $aVariable to $anotherVariable, a copy of the value held in $aVariable would be stored in $anotherVariable. Subsequently changing the value of $aVariable would have no effect on the contents of $anotherVariable. Listing 4.2 illustrates this. Listing 4.2: Variables Are Assigned by Value 1: <html> 2: <head> 3: <title>Listing 4.2 Variables are assigned by value</title> 4: </head> 5: <body> 6: <?php 7: $aVariable = 42; 8: $anotherVariable = $aVariable; 9: // a copy of the contents of $aVariable is placed in $anotherVariable 10: $aVariable = 325; 11: print $anotherVariable; // prints 42 12: ?> 13: </body> 14: </html> This example initializes $aVariable, assigning the value 42 to it. $aVariable is then assigned to $anotherVariable. A copy of the value of $aVariable is placed in $anotherVariable. Changing the value of $aVariable to 325 has no effect on the contents of $anotherVariable. The print statement demonstrates this by outputting 42 to the browser. In PHP4, you can change this behavior, forcing a reference to $aVariable to be assigned to $anotherVariable, rather than a copy of its contents. This is illustrated in Listing 4.3. Listing 4.3: Assigning a Variable by Reference 1: <html> 2: <head> 3: <title>Listing 4.3 Assigning a variable by reference</title> 4: </head> 5: <body> 53 6: <?php 7: $aVariable = 42; 8: $anotherVariable = &$aVariable; 9: // a copy of the contents of $aVariable is placed in $anotherVariable 10: $aVariable= 325; 11: print $anotherVariable; // prints 325 12: ?> 13: </body> 14: </html> We have added only a single character to the code in Listing 4.2. Placing an ampersand (&) in front of the $aVariable variable ensures that a reference to this variable, rather than a copy of its contents, is assigned to $anotherVariable. Now any changes made to $aVariable are seen when accessing $anotherVariable. In other words, both $aVariable and $anotherVariable now point to the same value. Because this technique avoids the overhead of copying values from one variable to another, it can result in a small increase in performance. Unless your script assigns variables intensively, however, this performance gain will be barely measurable. Note References to variables were introduced with PHP4. Data Types Different types of data take up different amounts of memory and may be treated differently when they are manipulated in a script. Some programming languages therefore demand that the programmer declare in advance which type of data a variable will contain. PHP4 is loosely typed, which means that it will calculate data types as data is assigned to each variable. This is a mixed blessing. On the one hand, it means that variables can be used flexibly, holding a string at one point and an integer at another. On the other hand, this can lead to confusion in larger scripts if you expect a variable to hold one data type when in fact it holds something completely different. Table 4.1 shows the six data types available in PHP4. Table 4.1: Data Types Type Example Description Integer 5 A whole number 54 Double 3.234 A floating-point number String "hello" A collection of characters Boolean true One of the special values true or false Object See Hour 8, "Objects" Array See Hour 7, "Arrays" Of PHP4's six data types, we will leave arrays and objects for Hours 7 and 8. You can use PHP4's built-in function gettype() to test the type of any variable. If you place a variable between the parentheses of the function call, gettype() returns a string representing the relevant type. Listing 4.4 assigns four different data types to a single variable, testing it with gettype() each time. Note You can read more about calling functions in Hour 6, "Functions." Listing 4.4: Testing the Type of a Variable 1: <html> 2: <head> 3: <title>Listing 4.3 Testing the type of a variable</title> 4: </head> 5: <body> 6: <?php 7: $testing = 5; 8: print gettype( $testing ); // integer 9: print "<br>"; 10: $testing = "five"; 11: print gettype( $testing ); // string 12: print("<br>"); 13: $testing = 5.0; 55 14: print gettype( $testing ); // double 15: print("<br>"); 16: $testing = true; 17: print gettype( $testing ); // boolean 18: print "<br>"; 19: ?> 20: </body> 21: </html> This script produces the following: integer string double boolean An integer is a whole or real number. In simple terms, it can be said to be a number without a decimal point. A string is a collection of characters. When you work with strings in your scripts, they should always be surrounded by double (") or single (') quotation marks. A double is a floating-point number. That is, a number that includes a decimal point. A boolean can be one of two special values, true or false. Note Prior to PHP4, there was no boolean type. Although true was used, it actually resolved to the integer 1. Changing Type with settype() PHP provides the function settype() to change the type of a variable. To use settype(), you must place the variable to change (and the type to change it to) between the parentheses and separated by commas. Listing 4.5 converts 3.14 (a double) to the four types that we are covering in this hour. Listing 4.5: Changing the Type of a Variable with settype() 1: <html> 2: <head> 3: <title>Listing 4.5 Changing the type of a variable with settype()</title> 4: </head> [...]... ( string ) $undecided; 12: print gettype( $holder ); // string 13: print " $holder"; // 3.14 14: $holder = ( integer ) $undecided; 15: print gettype( $holder ); 16: print " $holder"; // integer // 3 17: $holder = ( double ) $undecided; 18: print gettype( $holder ); // double 19: print " $holder"; // 3.14 20 : $holder = ( boolean ) $undecided; 21 : print gettype( $holder ); 22 : print... boolean ); 20 : print gettype( $undecided ); // boolean 21 : print " $undecided"; // 1 22 : ?> 23 : 24 : In each case, we use gettype() to confirm that the type change worked and then print the value of the variable $undecided to the browser When we convert the string "3.14" to an integer, any information beyond the decimal point is lost forever That's why $undecided still contains 3 after... loop continues indefinitely Listing 5.6 creates a while loop that calculates and prints multiples of two Listing 5.6: A while Statement 1: 2: 3: Listing 5.6 4: 5: 6: 14: 15: In this example, we initialize... of distinguishing between a constant and a string within quotation marks Predefined Constants PHP automatically provides some built -in constants for you FILE , for example, returns the name of the file currently being read by the interpreter LINE returns the line number of the file These constants are useful for generating error messages You can also find out which version of PHP is interpreting the... Listing 4.7 defines and accesses a constant Listing 4.7: Defining a Constant 1: 2: 3: Listing 4.7 Defining a constant 4: 5: 6: 10: 11: Notice that we used the concatenation operator to append the value held by our constant to the string "Welcome" This is because the interpreter... 8: print gettype( $undecided ); // double 9: print " $undecided"; // 3.14 10: settype( $undecided, string ); 11: print gettype( $undecided ); // string 12: print " $undecided"; // 3.14 13: settype( $undecided, integer ); 14: print gettype( $undecided ); // integer 15: print " $undecided"; // 3 16: settype( $undecided, double ); 17: print gettype( $undecided ); // double 18: print "... The single operand is not true Why are there two versions of both the or and the and operators? The answer lies in operator precedence, which you will look at later in this section Automatically Incrementing and Decrementing an Integer Variable When coding in PHP, you will often find it necessary to increment or decrement an integer variable You will usually need to do this when you are counting the... $holder"; 23 : ?> // boolean // 1 58 24 : 25 : We never actually change the type of $undecided, which remains a double throughout In fact, by casting $undecided, we create a copy that is then converted to the type we specify This new value is then stored in the variable $holder Because we are working with a copy of $undecided, we never discard any information from it as we did in Listing 4.5... The principal difference between settype() and a cast is the fact that casting produces a copy, leaving the original variable untouched Listing 4.6 illustrates this Listing 4.6: Casting a Variable 1: 2: 3: Listing 4.6 Casting a variable 4: 5: 6: . 7: $testing = 5; 8: print gettype( $testing ); // integer 9: print "<br>"; 10: $testing = "five"; 11: print gettype( $testing ); // string 12: print("<br>");. brings some of the previous code fragments together into a single script using a string stored in a variable to initialize and access a variable called $user. Listing 4.1: Dynamically Setting. When printing a boolean in PHP, true is represented as 1 and false as an empty string, so $undecided is printed as 1. 57 Changing Type by Casting By placing the name of a data type in brackets
- Xem thêm -

Xem thêm: SAMS Teach Yourself PHP4 in 24 Hours phần 2 pps, SAMS Teach Yourself PHP4 in 24 Hours phần 2 pps, SAMS Teach Yourself PHP4 in 24 Hours phần 2 pps

Từ khóa liên quan

Gợi ý tài liệu liên quan cho bạn