3.2. Coding Building BlocksTo write programs in PHP that do something useful, you'll need to understand blocks of reusable code called functions or methods, and then how to temporarily store information that cannot be executed in variables. We talk about evaluations, which are basically things that allow your code to make intelligent decisions based on mathematical principles and user input. 3.2.1. VariablesSince you haven't done any programming, we understand that variables are a new concept. A variable stores a value, such as the text string "Hello World!" or the integer value 1. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again for the entire life of the variable, which can be frustrating and tedious. Figure 3-2 shows a newly created variable that has been assigned a value of 30. Figure 3-2. A variable holding a valueIn PHP, you define a variable with the following form: $variable_name = value; Pay very close attention to some key elements in the form of variables. The dollar sign ($) must always fill the first space of your variable. The first character after the dollar sign must be a letter or underscore. It can't under any circumstances be a number; otherwise, your code will not execute, so watch those typos!
To create a simple PHP variable as in Figure 3-2, enter: <?php $age = 30; ?> This code takes the variable named age and assigns it the number 30. You can use variables without worrying about the specific value assigned to them. (PHP is not strongly typed, if you have a background in Java or C.) If you were to assign a new value to a variable with the same name, as happens in Example 3-6, the old name would be overwritten and you would have a potential logic error in your code. Example 3-6. Reassigning a variable
The new value of $age replaces the old, and this is the output: 31 3.2.1.1. Reading a variable's valueTo access the value of a variable that's already been assigned, simply specify the dollar sign ($) followed by the variable name, and use it as you would the value of the variable in your code. For example, Figure 3-3 displays the value of $age. You don't necessarily have to clean up your variables when your program finishes. They're temporary, since PHP automatically cleans them up when you're done using them. Sort of like how Microsoft Word creates a temp file of your document, so when you close the document, the temp file deletes itself. 3.2.1.2. Variable typesVariables all store certain types of data. PHP automatically picks a data variable based on the value assigned. These data types include strings, numbers, and more complex types such as arrays. We'll discuss arrays later. What's important to know is that unless you have a reason to care about the data type, PHP handles all of the details, so you need not worry about that. However, it's good practice to learn about data types. In situations where a specific type of data is required, such as the mathematical division operation, PHP attempts to convert the data types automatically. If you have a string with a single "2," it will be converted to an integer value of 2. This conversion is nearly always exactly what you want PHP to do and makes coding seamless for you. 3.2.1.3. Variable scopePHP helps keep your code organized by making sure that, if you use code that someone else wrote (and you very likely will), the names of the variables in your code don't clash with other previously written variable names. For example, if you're using a variable called $name that has a value of Bill, and you use someone else's code that also has a variable called $name but uses it to keep track of the filename log.txt, your value could get overwritten. Your code's value for $name of Bill will be replaced by log.txt, and your code will say "Hello log.txt" instead of "Hello Bill", which would be a big problem. To solve this problem, PHP organizes code into functions. Functions allow you to group a chunk of code together and execute that code by its name. To keep variables in your code separate from variables in functions, PHP provides separate storage of variables within each function. This separate storage space means that the scope, or where a variable's value can be accessed, is the local storage of the function. Figure 3-3 demonstrates how there are distinct storage areas for a function's variables. Figure 3-3. The $age variable has a separate value outside of the birthday function's variable storage areaExample 3-7 shows how the variable you use outside of the function isn't changed by the code within the function. Don't worry too much about understanding how the function works, as it has its own set of unique variables. Example 3-7. The default handling of variable scope
This displays: 30 Although calling the function birthday assigns 1 to the variable $age, it's not accessing the same variable that was defined on the main level of the program. Therefore, when you print $age, you see the original value of 30. The bolded part of the code is what is seen when $age = is printed, because $age in birthday is a separate variable. All of this is great, but if you really want to access or change the variable $age that was created outside the birthday function, you would use a global variable. 3.2.1.3.1. Global variablesGlobal variables allow you to cross the boundary between separate functions to access a variable's value. The global statement specifies that you want the variable to be the same variable everywhere, or globally. Figure 3-4 shows how a global variable is accessible to everything. Figure 3-4. The global keyword creates one global variable called $ageExample 3-8 shows that use of a global variable can result in a change. Example 3-8. Using a global variable changes the result
This displays: 31 Global variables should be used sparingly, since it's easy to accidentally modify a variable by mistake. This kind of error can be very difficult to locate. Additionally, when we discuss functions in detail, you'll learn that you can send in values to functions when you call them and get values returned from them when they're done. That all boils down to the fact that you really don't have to use global variables. If you want to use a variable in a specific function without losing the value each time the function ends, but you don't want to use a global variable, you would use a static variable. 3.2.1.3.2. Static variablesStatic variables provide a variable that isn't destroyed when a function ends. You can use the static variable value again the next time you call the function.
The easiest way to think about this is to realize that the variable is a global to just that function. A static keyword is used to dictate that the variable you're working with is static, as illustrated in Figure 3-5. Figure 3-5. The static variable creates a persistent storage space for $age in birthdayIn Example 3-9, we use the static keyword to define these function variables. Example 3-9. A static variable remembering its last value
This displays: Birthday number 1 Birthday number 2 Age: 30
The value of $age is now retained each time the birthday function is called. The value will stay around until the program quits. We've discussed two types of variables, but there's one more to discuss: super global. 3.2.1.3.3. Super global variablesPHP uses special variables called super globals to provide information about the PHP script's environment. These variables don't need to be declared as global; they are automatically available and provide important information beyond the script's environment, such as values from a user input. Since PHP 4.01, the super globals are defined in arrays. Arrays are special collections of values that we'll discuss in Chapter 7. The older super global variables such as those starting with $HTTP_* that were not in arrays still exist, but their use is not recommended as they are less secure. Table 3-1 shows the existing arrays since PHP 4.01.
An example of a super global is PHP_SELF. This variable contains the name of the running script and is part of the $_SERVER array, as shown in Example 3-10. Example 3-10. PHP_SELF being used with a file called test.php
This outputs: /test.php This variable is especially useful, as it can be used to call the current script again when processing a form. Super global variables provide a convenient way to access information about a script's environment from server settings to user inputted data. Now that you've got a handle on variables and scope, we can talk about what types of information variables hold. 3.2.2. StringsVariables can hold more than just numbers. They can hold characters and strings, or an ordered list of characters. Figure 3-6 demonstrates how an ordered list of characters becomes a string. Figure 3-6. How individual characters form a stringA string can be used directly in a function call or it can be stored in a variable. In Example 3-11, we create the exact same string twice: first we store it in a variable, and then we place the string directly into a function. Example 3-11. Working with strings
In Example 3-12, the first string is stored in the variable $my_string, while the second string is used in the echo function and isn't stored. Remember to save your strings into variables if you plan on using them more than once! Strings are flexible. You can even insert variables into string definitions when using double quotes to start and end your string, as shown in Example 3-12. Using a single quote to start and end your string does not allow a variable to be placed in the string. Example 3-12. Using a variable in a string definition
This example displays "Time for Margaritaville - Suntan Oil Application!" Double quotes are used in the above string, but single quotes or apostrophes can both be used as long as you won't be inserting variable values; see Example 3-13. Example 3-13. Single quotes used in a string assignment
Remember, if you want to use a single quote within a string marked with single quotes, you have to escape the single quote with a backslash (\). Double quotes allow the use of many special escaped characters that you can't use with a single quote string, such as an apostrophe. If you had escaped an apostrophe with a backslash in a double-quoted string, the backslash would show up when you output the string. 3.2.2.1. Special characters in stringsTab, newline, and carriage returns are all examples of extra, yet ignorable, whitespace (see Example 3-14). If you are writing to a file, a valuable tool is an escaped character. One downside of using the apostrophe to start and end a string is that you can't include a variable. This leads us to be careful about using HTML markup or any other string that includes quotes. Example 3-14. Various special characters in string assignments
The echo function uses quotes to define the start and end of a string, so you must use one of the following tactics if your string contains quotations:
In Examples 3-15 and 3-16, the wrong and right use of the echo function is demonstrated. Example 3-15. Using echo with special characters
In the first echo example, we forgot to escape the double quotes that surround the specialH2, which is HTML text. Attempting to display this page produces the error: Parse error: parse error, unexpected T_STRING, expecting ',' or ';' in /home/www/html/oreilly/ch3/parse.php on line 3 If you see that error, start by checking your single and double quotes to make sure they all match up correctly, as in Example 3-16. Example 3-16. Correct escaping of special characters
Example 3-16 escapes quotations by placing a slash in front of each one (\"). The slash tells PHP that you want the quotation to be used within the string and not ending echo's string. You can also use an apostrophe (') to mark the beginning and end of a string.
You'll find that when you're working with strings, you'll want to combine them. This is actually like working with shorthand instead of writing out each and every word. 3.2.2.2. Comparing stringsPHP has functions to compare strings that aren't exactly alike. For example, you may want to consider "Bill" to be the same as "BILL," ignoring the case of the string. Use strcmp (string1, string2) to compare two strings including the case. The return value is 0 if the two strings have the same text. Any nonzero value indicates they are not the same. Use strcasecmp (string1, string2) to compare two strings without comparing the case. The return value is 0 if the two strings have the same text. Any nonzero value indicates they are not the same. Example 3-17 compares "Bill" to "BILL" without considering the case. Example 3-17. Using strcasecmp to compare two strings
This returns: They match. 3.2.3. ConcatenationConcatenation combines one or more text strings and variables, as shown in Example 3-18. When performing this combination, you save yourself the hassle of creating numerous echo statements, or in other words, you build up a string and use it. Example 3-18. Concatenating strings together
The output of your code looks like Figure 3-7 in your browser window. Figure 3-7. Concatenation outputVariables and text strings are joined together with a period (.). This can be done multiple times, as shown in Figure 3-8. Figure 3-8. How strings come together with concatenationSince your time is finite, tying strings and variables together helps you create dynamic web sites faster. 3.2.3.1. Combining strings with other typesIf you combine a string with another data type, such as a number, the result is also a string, as shown in Example 3-19. Example 3-19. Combining a string and a number
This displays: This is an example of 3 in the middle of a string. $str contains a string even though a number was inserted into the middle. 3.2.4. ConstantsYou can define constants in your program. A constant, like its name implies, cannot change its value during the execution of your program. It's defined using the define function, which takes the name of the constant as the first parameter and the values as the second parameter. The definition of a constant is global and can be defined as any simple (scalar) data type such as a string or a number. You can get the value of a constant by simply specifying its name; see Example 3-20. Unlike how you handle variables, you should not put the dollar sign ($) before a constant. A cool thing you do with constants is using the function constant(name) to return a constant's value when the constant's name is determined dynamically. Or you could use get_defined_constants to return a list (as an array) of all your defined constants. If you're unsure about the arguments to a function, you can search the PHP site at http://www.php.net to find function parameters and return values. These are the differences between constants and variables:
Example 3-20 demonstrates how to use a constant in your program. Example 3-20. Using a constant in your program
This outputs: Hello world! Constants are useful for values that you need to make sure don't change, such as a configuration file location. If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a stringfor example, CONSTANT as opposed to "CONSTANT". If the define line of Example 3-20 is commented out, the output becomes: HELLO 3.2.4.1. Predefined constantsPHP provides a few constants that are predefined similar to the way we have some super globals. Examples of these include __FILE__, which returns the name of the PHP file that's being executed, and __LINE__, which returns the line number in that file. They can be handy for generating an error message as they tell you where in your code the error occurred, as shown in Example 3-21. Example 3-21. Echoing the line and file predefined constants for a script called predefined_constants.php
This returns: Executing line 2 of PHP script /home/www/html/oreilly/ch3/predefined_constants.php. The path to your script may be different than the example. On Windows, it's likely to be C:\Program Files\Apache Group\htdocs\c3. 3.2.5. Doing MathVariables can hold numbers, too, and it's useful to perform mathematical operations on those numbers. All fundamental mathematical functions are available using PHP. You may feel like you're back in middle school algebra, but the basic functions are just like they were then: adding, subtracting, multiplying, and dividing. In Example 3-22, the divide (/) operator calculates the percentage from its operands sunny days and total days in a year to get a percentage of approximately 82 percent. Example 3-22. PHP mathematical function usage
In Figure 3-9, the 82 percent outcome from our example code displays in your browser window. Figure 3-9. Mathematical operation outputPHP also supports the mathematical operations listed in Table 3-2.
The operators can take whole numbers or decimal numbers as their input.
Of course, you can do all sorts of complex mathematical operations such as trigonometry, and there is a specific order in which the math operators are applied, but we'll discuss those in the next chapter. You can also use http://www.php.net by entering Math into their search tool, which provides a link to http://us3.php.net/manual/en/ref.math.php that gives you a detailed listing and usage of all of the math functions. 3.2.5.1. Combined assignmentCombined assignment operators provide a shortcut for performing two common tasks at the same time. They combine reading a variable, performing an operation on it, and placing the result back in the same variable. The operations are mostly mathematical but can also include other operators like concatenation. Combined assignment operators take the form the arithmetic operator directly followed by an equals sign (=). For example, the statement: $counter=$counter+1; is equivalent to: $counter+=1; Which is shorthand for taking the value in $counter, adding one to it, and then saving the result back in $counter. Table 3-3 lists the most common combined assignment operators.
You'll find that these operators are very handy when creating your dynamic web pages. They'll also be used frequently in our examples. They have the added benefit of reducing the chance that you'll have a typo in your variable name, since you need to specify the variable name once only. Along the same lines as combined operators comes a shorthand method for adding one or subtracting one from a variable. 3.2.5.2. Autoincrement and autodecrementIt's very common when writing your code to ether increment or decrement a variable by one. It's so common that PHP has a special shortcut for doing it. The autoincrement operator is ++ and is used like this: $counter++; What we did was: $counter+=1; Example 3-23 adds one to $counter. Example 3-23. Using autoincrement to add to a variable
This produces: 2 The same concept applies to the automatic decrement operator, --. Example 3-24 subtracts one from $counter. Example 3-24. Using the autodecrement operator
This produces: 0 This notation is used frequently when doing repetitive tasks to keep track of how many times you've done them. 3.2.5.3. Pre-increment and -decrementIf you're incrementing or decrementing at the same time that you're also comparing the value of the variable, such as in a for or while loop, a pre-increment or -decrement can affect the value that's used for the comparison. When using the pre- operations, the value changes before the comparison, which is different than the de facto post-processing. For example: --$counter; or: ++$counter; Both of the operators still change the value of the counter variable, but they change the value sooner. If you are using that variable in a test, you'll see the current value before the change. We'll talk more about testing the values of variable executing blocks of code repetitively in the next chapter. Example 3-25 shows how these operators work. Example 3-25. Using pre- and post-increment
This produces: Preincrement: 2 Value afterwords: 2 Postincrement: 1 Value afterwords: 2 Notice that in Example 3-25, the value after a post- or pre-increment is always 2. When using the pre-increment, the value is 2 in the echo statement that contains the combined operator. In this chapter, you've learned about the basic concepts for writing PHP scripts. You've introduced variables that can remember information while our scripts execute. You know how to store values in variables and access those values. You don't have to worry about specifying data types, because PHP attempts to convert types automatically. You've also learned how to do basic mathematical operations and the shortcuts for the most common combined assignment operators. These concepts will form the basis for the rest of what you learn about PHP programming, including building expressions. The next chapter will introduce more complicated PHP code such as arrays, including looping and conditional logic. After that, we'll be able to jump into MySQL and how it operates as a database. |