Archive for May, 2007

91Chapter 6Control and FunctionsBranching and HTML ModeAs you (Unable to start debugging on the web server)

Tuesday, May 8th, 2007

91Chapter 6Control and FunctionsBranching and HTML ModeAs you may have learned from earlier chapters, you should feel free to use the PHP tags to switchback and forth between HTML mode and PHP mode, whenever it seems convenient. If you needto include a large chunk of HTML in your page that has no dynamic code or interpolated vari- ables, it can be simpler and more efficient to escape back into HTML mode and include it literallythan it is to send it using printor echo. What may not be as obvious is that this strategy works even inside conditional structures. That is, you can use PHP to decide what HTML to send and then send that HTML by temporarily escap- ing back to HTML mode. For example, the following cumbersome code uses printstatements to construct a completeHTML page based on the supposed gender of the viewer. (We re assuming a nonexistentBoolean function called female()that tests for this.) The women-only site
); print( ); print( This site has been specially constructed ); print( for women only.
No men allowed here! ); } else{ print( The men-only site
); print( ); print( This site has been specially constructed ); print( for men only.
No women allowed here! ); } ?> Instead of all these printstatements, we can duck back into HTML mode within each of the twobranches: The women-only site This site has been specially constructedfor women only.
No men allowed here! Continued08
Note: If you are looking for reliable webhost to maintain and run your java application check Vision java hosting services

Jetty web server - 90Part IPHP: The BasicsElse attachmentAt this point, former

Tuesday, May 8th, 2007

90Part IPHP: The BasicsElse attachmentAt this point, former Pascal programmers may be warily wondering about elseattachment that is, how does an elseclause know which ifit belongs to? The rules are simple and arethe same as in most languages other than Pascal. Each elseis matched with the nearestunmatched ifthat can be found, while respecting the boundaries of braces. If you want tomake sure that an ifstatement stays solo and does not get matched to an else, wrap it up in braces like so: if ($num % 2 == 0) // $num is even? { if ($num > 2) print( num is not prime
); } elseprint( num is odd
); This code will print numisnotprimeif $numhappens to be an even number greater than 2, numisoddif $numis odd, and nothing if $numhappens to be 2. If we had omitted the curlybraces, the elsewould attach to the inner if, and so the code would buggily print numisoddif $numwere equal to 2 and would print nothing if $numwere actually odd. In this chapter s examples, we often use the modulus operator (%), which is explained inChapter 10. For the purposes of these examples, all you need to know is that if $x%$yiszero, $xis evenly divisible by $y. ElseifIt s very common to want to do a cascading sequence of tests, as in the following nested ifstatements: if ($day == 5) print( Five golden rings
); elseif ($day == 4) print( Four calling birds
); elseif ($day == 3) print( Three French hens
); elseif ($day == 2) print( Two turtledoves
); elseif ($day == 1) print( A partridge in a pear tree
); We have indented this code in to show the real syntactic structure of inclusions althoughthis is always a good idea, you will often see code that does not bother with this and whereeach elseline starts in the first column. NoteNote08
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision web and email hosting services

89Chapter 6Control and FunctionsIf-elseThe syntax for (Web hosting faq) ifis: if

Tuesday, May 8th, 2007

89Chapter 6Control and FunctionsIf-elseThe syntax for ifis: if (test) statement-1Or with an optional elsebranch: if (test) statement-1elsestatement-2When an ifstatement is processed, the testexpression is evaluated, and the result is inter- preted as a Boolean value. If testis true, statement-1is executed. If testis not true, andthere is an elseclause, statement-2is executed. If test is false, and there is no elseclause, execution simply proceeds with the next statement after the ifconstruct. Note that a statementin this syntax can be a single statement that ends with a semicolon, abrace-enclosed block of statements, or another conditional construct (which itself counts asa single statement). Conditionals can be nested inside each other to arbitrary depth. Also, theBoolean expression can be a genuine Boolean (TRUE, FALSE, or the result of a Boolean opera- tor or function), or it can be a value of another type interpreted as a Boolean. For the full story on how values of non-Boolean types are treated as Booleans, see Chapter 25. The short version is that the number 0, the string 0 , and the empty string, , are false, andalmost every other value is true. The following example, which prints a statement about the absolute difference betweentwonumbers, shows both the nesting of conditionals and the interpretation of the test asaBoolean: if ($first - $second) if ($first > $second) { $difference = $first - $second; print( The difference is $difference
); } else{ $difference = $second - $first; print( The difference is $difference
); } elseprint( There is no difference
); This code relies on the fact that the number 0is interpreted as a false value if the differ- ence is zero, then the test fails, and the no differencemessage is printed. If there is a difference, a further test is performed. (This example is artificial, because a test like $first!=$secondwould accomplish the same thing comprehensibly.) Cross- Reference08
Note: If you are looking for high quality webhost to host and run your jsp application check Vision florida web design services

88Part IPHP: The BasicsAs (Web server extensions) we will see, this

Monday, May 7th, 2007

88Part IPHP: The BasicsAs we will see, this is equivalent to: if ($first_num > $second_num) $max_num = $first_num; else$max_num = $second_num; but is somewhat more concise. BranchingThe two main structures for branching are if and switch. Ifis a workhorse and is usuallythe first conditional structure anyone learns. Switchis a useful alternative for certain situa- tions where you want multiple possible branches based on a single value and where a seriesof ifstatements would be cumbersome. Comparing Things That Are Not IntegersAlthough comparison operators work with numbers or strings, a couple of gotchas lurk here. First of all, although it is always safe to do less-than or greater-than comparisons on doubles (or even between doubles and integers), it can be dangerous to rely on equality comparisons ondoubles, especially if they are the result of a numerical computation. The problem is that arounding error may make two values that are theoretically equal differ slightly. Second, although comparison operators work for strings as well as numbers, PHP s automatictype conversions can lead to counterintuitive results when the strings are interpretable as numbers. For example, the code: $string_1 = 00008 ; $string_2 = 007 ; $string_3 = 00008-OK ; if ($string_2 < $string_1) print( $string_2 is less than $string_1
); if ($string_3 < $string_2) print( $string_3 is less than $string_2
); if ($string_1 < $string_3) print( $string_1 is less than $string_3
); gives this output (with comments added): 007 is less than 00008 // numerical comparison00008-OK is less than 007 // string comparison00008 is less than 00008-OK // string comp. - contradiction! When it can, PHP will convert string arguments to numbers, and when both sides can be treatedthat way, the comparison ends up being numerical, not alphabetic. The PHP designers view thisas a feature, not a bug. Our view is that if you are comparing strings that have any chance ofbeing interpreted as numbers, you re better off using the strcmp()function (see Chapter 10).
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check Vision professional web hosting services

87Chapter 6Control and (Professional web hosting) FunctionsWatch out for a very

Monday, May 7th, 2007

87Chapter 6Control and FunctionsWatch out for a very common mistake: confusing the assignment operator (=) with the com- parison operator (==). The statement if($three=$four).will (probably unexpectedly) set the variable $threeto be the same as $four; what s more, the test will be true if $fouris a true value! Operator precedenceAlthough overreliance on precedence rules can be confusing for the person who reads yourcode next, it s useful to note that comparison operators have higher precedence than Booleanoperators. This means that a test like the following: if ($small_num > 2 && $small_num < 5) ... doesn t need any parentheses other than those shown. String comparisonThe comparison operators may be used to compare strings as well as numbers (see the cautionary sidebar). We would expect the following code to print its associated sentence(with apologies to Billy Bragg): if (( Marx < Mary ) and( Mary < Marzipan )) { print( Between Marx and Marzipan in the ); print( dictionary, there was Mary.
); } The comparisons are case sensitive, and the only reason that this example will print anythingis because our values are case-consistent.Because of the capitalization of Dennis, the follow- ing will not print anything: if (( deep blue sea < Dennis ) and( Dennis < devil )) { print( Between the deep blue sea and ); print( the devil, that was me.
); } The ternary operatorOne especially useful construct is the ternary conditional operator, which plays a role some- where between a Boolean operator and a true branching construct. Its job is to take threeexpressions and use the truth value of the first expression to decide which of the other twoexpressions to evaluate and return. The syntax looks like: test-expression ? yes-expression : no-expressionThe value of this expression is the result of yes-expressionif test-expressionis true; otherwise, it is the same as no-expression. For example, the following expression assigns to $max_numeither $first_numor$second_num, whichever is larger: $max_num = $first_num > $second_num ? $first_num : $second_num; Caution08
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

Web hosting resellers - 86Part IPHP: The BasicsSo far, all we ve formally

Monday, May 7th, 2007

86Part IPHP: The BasicsSo far, all we ve formally covered are the TRUEand FALSEconstants and how to combinethem to make other true-or-false values. Now we ll move on to operators that actually let youmake meaningful Boolean tests. Comparison operatorsTable 6-2 shows the comparison operators, which can be used for either numbers or strings(although you should see the cautionary sidebar entitled Comparing Things That Are NotIntegers ). Table 6-2: Comparison OperatorsOperatorNameBehavior==EqualTrue if its arguments are equal to each other, falseotherwise!=Not equalFalse if its arguments are equal to each other, trueotherwiseGreater thanTrue if the left-hand argument is greater than itsright-hand argument, but false otherwise<=Less than or equal toTrue if the left-hand argument is less than its right- hand argument or equal to it, but false otherwise>=Greater than or equal toTrue if the left-hand argument is greater than its right- hand argument or equal to it, but false otherwise===IdenticalTrue if its arguments are equal to each other and ofthe same type, but false otherwise As an example, here are some variable assignments, followed by a compound test that isalways true: $three = 3; $four = 4; $my_pi = 3.14159; if (($three == $three) and($four === $four) and($three != $four) and($three < $four) and($three <= $four) and($four >= $three) and($three <= $three) and($my_pi > $three) and($my_pi <= $four)) print( My faith in mathematics is restored!
); elseprint( Sure you typed that right?
);
Note: If you are looking for cheap and reliable webhost to host and run your web application check Vision coldfusion web hosting services

Web hosting compare - 85Chapter 6Control and FunctionsThe &&and ||operators will be

Sunday, May 6th, 2007

85Chapter 6Control and FunctionsThe &&and ||operators will be familiar to C programmers. The !operator is usually callednot, since it negates the argument it operates on. As an example of using logical operators, consider the following expression: (($statement_1 && $statement_2) || ($statement_1 && !$statement_2) || (!$statement_1 && $statement_2) || (!$statement_1 && !$statement_2)) This is a tautology, meaning that it is always true regardless of the values of the statementvariables. There are four possible combinations of truth values for the two variables, each of which is represented by one of the &&expressions. One of these four must be true, andbecause they are linked by the ||operator, the entire expression must be true. Here s another, slightly trickier tautology using xor: (($statement_1 and $statement_2 and$statement_3) xor((!($statement_1 and $statement_2)) or(!($statement_1 and $statement_3)) or(!($statement_2 and $statement_3)))) In English, this expression says, Given three statements, one and only one of the followingtwo things hold either 1) all three statements are true, or 2) there are two statements thatare not both true. Precedence of logical operatorsJust as with any operators, some logical operators have higher precedence than others, although precedence can always be overridden by grouping subexpressions using parenthe- ses. The logical operators listed in declining order of precedence are: !, &&, ||, and, xor, or. Actually, and, xor, and orhave much lower precedence than the others, so that the assign- ment operator (=) binds more tightly than and, but less tightly than &&. A complete table of operator precedence and associativity can be found in the online manualat www.php.net. Logical operators short-circuitOne very handy feature of Boolean operators is that they associate left to right, and theyshort-circuit, meaning that they do not even evaluate their second argument if their truthvalue is unambiguous from their first argument. For example, imagine that you wanted todetermine a very approximate ratio of two numbers, but also wanted to avoid a possible division-by-zero error. You can first test to make sure that the denominator is not zero byusing the !=(not-equal-to) operator: if ($denom != 0 && $numer / $denom > 2) print( More than twice as much! ); In the case where $denomis zero, the &&operator should return false regardless of whetherthe second expression is true or false. Because of short-circuiting, the second expression isnot evaluated, so an error is avoided. In the case where $denomis not zero, the &&operatordoes not have enough information to reach a conclusion about its truth value, so the secondexpression is evaluated. Cross- Reference08
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision servlet hosting services

Make web site - 84Part IPHP: The BasicsIn this chapter, we also

Sunday, May 6th, 2007

84Part IPHP: The BasicsIn this chapter, we also look at how to use the large body of functions already provided inPHP and then, a bit later, how to define your own functions. Luckily, there is no real differencebetween using a built-in function and using your own functions. But first, let s discuss control. Boolean ExpressionsEvery control structure in this chapter has two distinct parts: the test(which determineswhich part of the rest of the structure executes), and the dependent codeitself (whether sepa- rate branches or the body of a loop). Tests work by evaluating a Boolean expression, anexpression with a result treated as either true or false. Boolean constantsThe simplest kind of expression is a simple value, and the simplest Boolean values are theconstants TRUEand FALSE. We can use these constants anywhere we would use a more com- plicated Boolean expression, and vice versa. For example, we can embed them in the test partof an if-elsestatement: if (TRUE) print( This will always print
); elseprint( This will never print
); Or equivalently: if (FALSE) print( This will never print
); elseprint( This will always print
); Logical operatorsLogical operatorscombine other logical (aka Boolean) values to produce new Boolean values. The standard logical operations (and, or, not, and exclusive-or) are supported by PHP, which has alternate versions of the first two, as shown in Table 6-1. Table 6-1: Logical OperatorsOperatorBehaviorandIs true if and only if both of its arguments are true. orIs true if either (or both) of its arguments are true. !Is true if its single argument (to the right) is false and false if its argument is true. xorIs true if either (but not both) of its arguments are true. &&Same as and, but binds to its arguments more tightly. (See the discussion ofprecedence later in the chapter.) ||Same as orbut binds to its arguments more tightly.
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision mysql5 web hosting services

Control andFunctionsIt s difficult to write interesting programs if (Web site design)

Sunday, May 6th, 2007

Control andFunctionsIt s difficult to write interesting programs if you can t make thecourse of program execution depend on anything. In a weak sense, the behavior of code that prints variables depends on the variablevalues, but that is as exciting as filling out a template. As program- mers, we want programs that react to something (the world, the timeof day, user input, or the contents of a database) by doing somethingdifferent. This kind of program reaction requires a control structure,which indi- cates how different situations should lead to the execution of differ- ent code. In Chapter 5, we informally used the ifcontrol structurewithout really explaining it; in this chapter, we lay out every kind ofcontrol structure offered by PHP and study their workings in detail. Experienced C programmers: Of all the features in PHP, control isprobably the most reliably C-like all the structures you are usedto are here, and they work the same way. The two broad types of control structures we will talk about arebranchesand loops.A branch is a fork in the road for a program s exe- cution depending on some test or other, the program goes eitherleft or right, possibly following a different path for the rest of the pro- gram s execution. A loop is a special kind of branch where one of theexecution paths jumps back to the beginning of the branch, repeatingthe test and possibly the body of the loop. Before we can make interesting use of control structures, however, we have to be able to construct interesting tests. We ll start from thevery simplest of tests, working our way up from the constants TRUEand FALSEand then move on to using these tests in more compli- cated code. Any real programming language has some kind of capability for proce- dural abstraction a way to name pieces of code so that you can usethem as building blocks in writing other pieces of code. Some script- ing languages lack this capability, and we can tell you from our ownsorrowful experience that complex server-side code can quicklybecome unmanageable without it. PHP s mechanism for this kind of abstraction is the function.Thereare really two kinds of functions in PHP those that have been builtinto the language by the PHP developers and those defined by indi- vidual PHP programmers. Note66CHAPTER …In This ChapterBoolean expressionsBranchingLoopingTerminating executionExceptionsUsing functionsFunction documentationDefining your ownfunctionsFunctions and variablescopeFunction scope …
Note: If you are looking for reliable webhost to maintain and run your java application check Vision java hosting services

82Part IPHP: The Basicswill produce the following output (Virtual web hosting)

Sunday, May 6th, 2007

82Part IPHP: The Basicswill produce the following output in the browser: The antelope has 1 head(s). The antelope has 4 leg(s). The values for the variables we included in the string have been neatly spliced into the printedoutput. This makes it very easy to quickly produce Web pages with content that varies depend- ing on how variables have been set. It is not the result of any magical properties of print, however the magic is really happening in the interpretation of the quoted string itself. HTML and linebreaksOne mistake often made by new PHP programmers (especially those from a C background) isto try to break lines of text in their browsers by putting end-of-line characters ( n ) in thestrings they print. To understand why this doesn t work, you have to distinguish the outputofPHP (which is usually HTML code, ready to be sent over the Internet to a browser program) from the way that output is rendered by the user s browser. Most browser programs willmake their own choices about how to split up lines in HTML text, unless you force a linebreak with the
tag. End-of-line characters in strings will put line breaks in the HTMLsource that PHP sends to your user s browser (which can still be useful for creating readableHTML source), but they will usually have no effect on the way that text looks in a Web page. SummaryPHP code follows a basic set of syntactical rules, mostly borrowed from programming lan- guages such as C and Perl. The syntactical requirements of PHP are minimal, and in generalPHP tries to display results when it can rather than generating an error. PHP has eight types: integer, double, Boolean, NULL, string, array, object, and resource. Fiveof these are simple types: Integers are whole numbers, doubles are floating-point numbers, Booleans are true-or-false values, NULL has just one value (NULL), and strings are sequencesof characters. Arraysare a compound type that holds other PHP values, indexed either byintegers or by strings. Objectsare instances of programmer-defined classes, which can con- tain both member variables and member functions, and which can inherit functions and datatypes from other classes. (We address arrays in Chapter 9 and objects in Chapter 20.) Finally, resourcesare special references to memory allocated from external programs, which memoryPHP frees automatically when they are no longer needed (we cover resources in Chapter 25). Only values are typed in PHP variables have no inherent type other than the value of theirmost recent assignment. PHP automatically converts value types as demanded by the contextin which the value is used. The programmer can also explicitly control types by means ofboth conversion functions and type casts. PHP code is whitespace insensitive, and although variable names are case sensitive, basiclanguage constructs and function names are not. Simple PHP expressions are combined intolarger expressions by operators and function calls, and statements are expressions with a ter- minating semicolon. Variables are denoted by a leading $character and are assigned usingthe =operator. They need no type declarations and have reasonable default values if usedbefore they are assigned. Variable scope is global except inside the body of functions, whereit is local to the function unless explicitly declared otherwise. The simplest way to send output to the user is by using either echoor print, which outputtheir string arguments. They are particularly useful in combination with doubly quotedstrings, which automatically replace embedded variables with their values. …
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision best web hosting services