Archive for August, 2007

110Part IPHP: The BasicsThe default (Java web server) error-reporting setting in

Friday, August 17th, 2007

110Part IPHP: The BasicsThe default error-reporting setting in PHP5 reports on every kind of error except runtimenotices, which are the least serious condition that is detected. The reason you see warningsabout too few arguments to a function is that this is treated as a runtime-warning situation(the next most serious category). If you really need function calls that sometimes provide toofew arguments and seeing warnings is unacceptable, you have two options for suppressingthe warnings: .You can temporarily change the value of error reporting in your script, with a statementlike error_reporting(E_ALL-(E_NOTICE+E_WARNING));.This will turn off both run- time notices and runtime warnings from the point where it appears in your script up tothe next error_reporting()statement (if any). (Note that this is dangerous, as lots ofother problems might produce warnings besides the one you re interested in.) .You can suppress errors for any single expression by using the error-control operator@, which you can put in front of any expression to suppress errors from that expressiononly. For example, if the function call my_function()is producing a warning, @my_function()will not. Note that this is dangerous as well because all types oferrors except for parse errors will be suppressed. We don t advise using either of these workarounds, but we provide them because we are suchnonjudgmental people by nature. PHP actually provides ways to write functions that expect vari- able numbers of arguments (see the Variable Numbers of Arguments section in Chapter 26), and using them is a much better idea than shooting the messenger. Rather than decreasing PHP s reportage of errors, we advise increasing it to the maximumlevel possible when you are developing new code. You can do this globally by changing the php.inifile (see Chapter 30) or simply by including the statement error_reporting(E_ALL);at the top of your scripts. Among other things, this increase in reportage willmean that you will be warned about variables you have forgotten to assign, which is one ofthe most frequent causes of time-wasting bugs. Too many argumentsIf you hand too many arguments to a function, the excess arguments will simply be ignored, even when error reporting is set to E_ALL. As we will see in Chapter 26, this tolerance turnsout to be helpful in defining functions that can take a variable number of arguments. Functions and Variable ScopeAs we said in Chapter 5, outside of functions, the rules about variable scope are simple: Assign a variable anywhere in the execution of a PHP code file, and the value will be there for you later in that file s execution. The rules become somewhat more complicated in thebodies of function definitions, but not much. The basic principle governing variables in function bodies is: Each function is its own littleworld. That is, barring some special declarations, the meaning of a variable name inside afunction has nothing to do with the meaning of that name elsewhere. (This is a feature, not abug you want functions to be reusable in different contexts, and so having the behavior beindependent of the context is a good thing. If not for this kind of scoping, you would waste alot of time chasing down bugs caused by using the same variable name in different parts ofyour code.) Tip08
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Web site counters - 109Chapter 6Control and FunctionsAlternatively, if the only way

Thursday, August 16th, 2007

109Chapter 6Control and FunctionsAlternatively, if the only way we ever use these price comparisons is to print which deal ispreferred, we can include the printing in the function, like this: function print_better_deal ($amount_1, $price_1, $amount_2, $price_2) { $per_amount_1 = $price_1 / $amount_1; $per_amount_2 = $price_2 / $amount_2; if ($per_amount_1 < $per_amount_2) print( The first deal is better!
); elseprint( The second deal is better!
); } $liters_1 = 1.0; $price_1 = 1.59; $liters_2 = 1.5; $price_2 = 2.09; print_better_deal($liters_1, $price_1, $liters_2, $price_2); Our first function used the returnstatement to send back a Boolean result, which was usedin an iftest. The second function has no return statement, because it is used for the sideeffect of printing text to the user s browser. When the last statement of this function is exe- cuted, PHP simply moves on to executing the next statement after a function call. Formal parameters versus actual parametersIn the preceding examples, the arguments we passed to our functions happened to be vari- ables, but this is not a requirement. The actual parameters (that is, the arguments in the function call) may be any expression that evaluates to a value. In our examples, we couldhave passed numbers to our function calls rather than variables, as in: print_better_deal(1.0, 1.59, 1.5, 2.09); Also, notice that in the examples we had a couple of cases where the actual parameter vari- able had the same name as the formal parameter (for example, $price_1), and we also hadcases where the actual and formal names were different. ($liters_1is not the same as$amount_1.) As we will see in the next section, this name agreement doesn t matter eitherway the names of a function s formal parameters are completely independent of the worldoutside the function, including the function call itself. Argument number mismatchesWhat happens if you call a function with fewer arguments than appear in the definition, orwith more? As you might have come to expect by now, PHP handles this without anythingcrashing, but it may print a warning depending on your settings for error reporting. Too few argumentsIf you supply fewer actual parameters than formal parameters, PHP will treat the unfilled for- mal parameters as if they were unbound variables. However, under the usual settings forerror reporting in PHP5, you will also see a warning printed to the browser.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

Web hosting contract - 108Part IPHP: The Basics3.The statements in the body

Wednesday, August 15th, 2007

108Part IPHP: The Basics3.The statements in the body of the function are executed. If any of the executed state- ments are returnstatements, the function stops and returns the given value. Otherwise, the function completes after the last statement is executed, without returning a value. The alert and experienced programmer will have noticed that the preceding descriptionimplies call-by-value, rather than call-by-reference. In Chapter 26, we explain the differenceand show how to get call-by-reference behavior. Function definition exampleAs an example, imagine that we have the following code that helps decide which size of bot- tled soft drink to buy. (This is sometime next year, when supermarket shoppers routinely usetheir wearable wireless Web browsers to get to our handy price-comparison site.) $liters_1 = 1.0; $price_1 = 1.59; $liters_2 = 1.5; $price_2 = 2.09; $per_liter_1 = $price_1 / $liters_1; $per_liter_2 = $price_2 / $liters_2; if ($per_liter1 < $per_liter2) print( The first deal is better!
); elseprint( The second deal is better!
); Because this kind of comparison happens in our Web site code all the time, we would like tomake part of this a reusable function. One way to do this would be the following rewrite: function better_deal ($amount_1, $price_1, $amount_2, $price_2) { $per_amount_1 = $price_1 / $amount_1; $per_amount_2 = $price_2 / $amount_2; return($per_amount_1 < $per_amount_2); } $liters_1 = 1.0; $price_1 = 1.59; $liters_2 = 1.5; $price_2 = 2.09; if (better_deal($liters_1, $price_1, $liters_2, $price_2)) print( The first deal is better!
); elseprint( The second deal is better!
); Our better_dealfunction abstracts out the three lines in the previous code that did thearithmetic and comparison. It takes four numbers as arguments and returns the value of aBoolean expression. As with any Boolean value, we can embed it in the test portion of an ifstatement. Although this function is longer than the original code, there are two benefits tothis rewrite: We can use the function in multiple places (saving lines overall), and if we decideto change the calculation, we have to make the change in only one place. Note08
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

107Chapter 6Control and (Web hosting contract) FunctionsFor the second type of

Wednesday, August 15th, 2007

107Chapter 6Control and FunctionsFor the second type of curiosity, your best bet is probably to use the hierarchical organiza- tion of the function reference, which is split (at press time) into about 108 chapters. Forexample, the substrfunction shown in the Headers in Documentation section is found inthe String Functions section. You can browse the chapter list of the function reference forthe best fit to the task you want to do. Alternatively, if you happen to know the name of afunction that seems to be in the same general area as your task, you can use the Quick Refbutton to jump to that chapter. Defining Your Own FunctionsUser-defined functions are not a requirement in PHP. You can produce interesting and usefulWeb sites simply with the basic language constructs and the large body of built-in functions. If you find that your code files are getting longer, harder to understand, and more difficult tomanage, however, it may be an indication that you should start wrapping some of your codeup into functions. What is a function? A functionis a way of wrapping up a chunk of code and giving that chunk a name, so that youcan use that chunk later in just one line of code. Functions are most useful when you will beusing the code in more than one place, but they can be helpful even in one-use situations, because they can make your code much more readable. Function definition syntaxFunction definitions have the following form: functionfunction-name($argument-1, $argument-2, ..) { statement-1; statement-2; … } That is, function definitions have four parts: .The special word function .The name that you want to give your function .The function s parameter list dollar-sign variables separated by commas .The function body a brace-enclosed set of statementsJust as with variable names, the name of the function must be made up of letters, numbers, and underscores, and it must not start with a number. Unlike variable names, function namesare converted to lowercase before they are stored internally by PHP, so a function is the sameregardless of capitalization. The short version of what happens when a user-defined function is called is: 1.PHP looks up the function by its name (you will get an error if the function has not yetbeen defined). 2.PHP substitutes the values of the calling arguments (or the actualparameters) into thevariables in the definition s parameter list (or the formal parameters).
We recommend high quality webhost to host and run your jsp application: christian web host services.

Web site design and hosting - 106Part IPHP: The BasicsThe largest section of the

Tuesday, August 14th, 2007

106Part IPHP: The BasicsThe largest section of the manual is the function reference, where each built-in function getsits own page of documentation. Typically, each group of functions has a page of general expla- nation, leading to pages for individual functions. Each function page starts off with the nameof the function and a one-line description. This is followed by a C-style header declaration ofthe function (explained in the next section), followed by a slightly longer description and possibly an example or two, and then (in the annotated manual) clarifications and gotchareports from users. Headers in documentationFor those unfamiliar with C function headers, the very beginning of a function documentationpage might be confusing. The format is: return-type function-name(type1 arg1, type2 arg2, . . .); This specifies the type of value the function is expected to return, the name of the function, and the number and expected types of its arguments. Here is a typical header description: string substr(string string, int start[, int length]); This says that the function substr()will return a string and expects to be given a string andtwo integers as its arguments. Actually, the square brackets around lengthindicate that thisargument is optional so substr()should be called either with a string and an int, or astring and two ints. Unlike in C, the argument types in these documentary headers are not absolute requirements. If you call substr()with a number as its first argument, you will not get an error. Instead, PHP will convert the first argument to a string as it begins to execute the function. However, the argument types do document the intent of the function s author, and it is a good ideaeither to use the function as documented or to understand the type conversion issues wellenough that you are sure the result will be what you expect. In general, the type names used in function documentation will be those of the basic types or of their aliases: integer (or int), double (or float, real), Boolean, string, array, object, resource, and NULL. In addition, you may see the types voidand mixed. The voidreturntype means that the function does not return a value at all, whereas the mixedargument typemeans that the argument might be of any type. Finding function documentationWhat s the best way to find information about a function in the manual? That is likely to dependon what kind of curiosity you have. The most common questions about functions are: .I want to use function X. Now, how does X work again? .I d really like to do task Y. Is there a function that handles that for me? For the first type of curiosity, the full version of the online manual offers an automatic lookupby function name. The Search For box in the upper-right-hand corner of the manual pagesdefaults to a mode where it searches for specific function names and displays the corre- sponding function page if found. (You can also make other choices, including searching themailing list or the entire online documentation the latter is a good choice when you don t know the name of the function you want, but can guess at words that appear on itsmanual page.)
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Web host forum - 105Chapter 6Control and FunctionsReturn values versus side effectsEvery

Monday, August 13th, 2007

105Chapter 6Control and FunctionsReturn values versus side effectsEvery function call is a PHP expression, and (just as with other expressions) there are onlytwo reasons why you might want to include one in your code: for the return valueor for theside effects. The return valueof a function is the value of the function expression itself. You can do exactlythe same things with this value as with the results of evaluating any other expression. Forexample, you can assign it to a variable, as in: $my_pi = pi(); Or you can embed it in more complicated expressions, as in: $approx = sqrt($approx) * sqrt($approx) Functions are also used for a wide variety of side effects, including writing to files, manipulatingdatabases, and printing things to the browser window. It s okay to make use of both return val- ues and side effects at the same time for example, it is very common to have a side-effectingfunction return a value that indicates whether or not the function succeeded. The result of a function may be of any type, and it is common to use the array type as a wayfor functions to return multiple values. Function DocumentationThe architecture of PHP has been cleverly designed to make it easy for other developers toextend. The basic PHP language itself is very clean and flexible, but there is not a lot there most of PHP s power resides in the large number of built-in functions. This means that devel- opers can contribute simply by adding new built-in functions, which is nice especiallybecause it does not change anything that PHP users may be relying on. Although this book covers many of these built-in functions, explaining some of them ingreater detail than the online manual can, the manual at www.php.netis the authoritativesource for function information. In this book, we get to choose our topics to some extent, whereas the PHP documentation group has the awesome responsibility of covering everyaspect of PHP in the manual. Also, although we hope to keep updating this book in future editions, the manual will have the freshest information on new additions to the ever-growingPHP functionality. It s worth looking at some of the different resources that the PHP site andmanual offer. Although the following information is correct at this writing, some details may become datedor inapplicable if the online manual is reorganized. To find the manual, head to www.php.net. A handy search bar at the top offers quick andeasy access to any individual part of the online documentation. Alternatively, find theDocumentation item at the top of the page. The Documentation page that this tab leads tohas links to manual information in a wide variety of formats. Our favorite version is thedefault (currently in the View Online row of the Formats table on the Documentation page), which allows users to post their own clarifying comments to each page. (Please note:Themanual annotation system is not the right place to post questions! For that, see the sectionon mailing lists at www.php.net, or see Appendix D. But it isthe right place to explain some- thing in your own words once you understand it. If you offer a better explanation, it mightwell show up in a later version of the documentation, which is a cool way to contribute. It salso definitely the right place to point out confusing aspects and potential gotchas.) Note08
If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.

Web design seattle - 104Part IPHP: The BasicsTable 6-3(continued) NameSyntaxBehaviorDo-whiledo statementPerform statementonce

Sunday, August 12th, 2007

104Part IPHP: The BasicsTable 6-3(continued) NameSyntaxBehaviorDo-whiledo statementPerform statementonce while (condition);unconditionally; then keeprepeating statement untilconditionbecomes false. (Thebreakand continuecommands are handled as inwhile.) Forfor (initial-expression;Evaluate initial-expressiononce termination-check;unconditionally. Then if loop-end-expression)termination-checkis true, evaluate statementstatement,and then loop-end- expression,and repeat that loopuntil termination-checkbecomesfalse. Clauses may be omitted, ormultiple clauses of the same kindcan be separated with commas amissing termination-check istreated as true. (The breakandcontinuecommands arehandled as in while.) Exit (or die)exit(message-string or Terminate script immediately, return-value), or without further parsing. The equivalentlydie()construct is an alias for die(message-string or exit(). return-value) Using FunctionsThe basic syntax for using (or calling) a function is: function_name(expression_1, expression_2, …, expression_n) This includes the name of the function followed by a parenthesized and comma-separated listof input expressions (which are called the argumentsto the function). Functions can be calledwith zero or more arguments, depending on their definitions. When PHP encounters a function call, it first evaluates each argument expression and thenuses these values as inputs to the function. After the function executes, the returned value (if any) is the result of the entire function expression. All the following are valid calls to built-in PHP functions: sqrt(9) // square root function, evaluates to 3rand(10, 10 + 10) // random number between 10 and 20strlen( This has 22 characters ) // returns the number 22pi() // returns the approximate value of piThese functions are called with 1, 2, 1, and 0 arguments, respectively.
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.

103Chapter 6Control and FunctionsTable 6-3: PHP (Top ten web hosting) Control StructuresNameSyntaxBehaviorIf(or

Saturday, August 11th, 2007

103Chapter 6Control and FunctionsTable 6-3: PHP Control StructuresNameSyntaxBehaviorIf(or if-else)if (test)statement-1Evaluate testand if it is true, -or-execute statement-1.If testis false if (test)and there is an elseclause, statement-1execute statement-2.The elseifelseconstruct is a syntactic shortcut for statement-2elseclauses, where the included -or-statement is itself an ifconstruct. if (test) statement-1Statements may be single elseif (test2)statements terminated with a statement-2semicolon or brace-enclosed elseblocks. statement-3Ternary operatorexpression-1 ?Evaluate expression-1and expression-2 :interpret it as a Boolean. If it is expression-3true, evaluate expression-2andreturn it as the value of the entireexpression. Otherwise, evaluateand return expression-3. Switchswitch(expression)Evaluate expression,and compare {its value to the value in each casecase value-1:clause. When a matching case is statement-1found, begin executing statements statement-2in sequence (including those from …later cases), until the end of the [break;]switchstatement or until a case value-2:breakstatement is encountered. statement-3The optional defaultcase will statement-4execute if no other case has …matched the expression. [break;] … [default: default-statement] } Whilewhile (condition)Evaluate conditionand interpret it statementas Boolean. If conditionis false, thewhileconstruct terminates. If itistrue, execute statement,andkeep executing it until conditionbecomes false. Terminate thewhileloop if the special breakcommand is encountered, and skipthe rest of the current iteration ifcontinueis encountered. Continued08
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Yahoo free web hosting - 102Part IPHP: The BasicsTerminating ExecutionSometimes you just have

Saturday, August 11th, 2007

102Part IPHP: The BasicsTerminating ExecutionSometimes you just have to give up, and PHP offers a construct that helps you do just that. The exit()construct takes either a string or a number as argument, prints out the argument, and then terminates execution of the script. Everything that PHP produces up to the point ofinvoking exit()is sent to the client browser as usual, and nothing in your script after thatpoint will even be parsed execution of the script stops immediately. If the argument givento exit is a number rather than a string, the number will be the return value for the script sexecution. Because exit is a construct, not a function, it s also legal to give no argument andomit the parentheses. The die()construct is an alias for exit()and so behaves exactly the same way. (We ll usu- ally use the die()version because we find the name more evocative.) So what s the point ofexit()and die()? One possible use is to cut off production of a Web page when your scripthas determined that there is no more interesting information to send, without bothering towrap up the different branches in a conditional construct. This usage can make long scriptssomewhat difficult to read and debug, however. A better use for die()is to make your crashes informative. It s good to get into the habit oftesting for unexpected conditions that would crash your script if they were true, and throwina die()statement with an informative message. If you re correct in your expectations, thedie()will never be invoked; if you re wrong, you will have an error message of your ownrather than a possibly obscure PHP error. For example, consider the following pseudocode, which assumes that we have functions to make a database connection and that we then usethat database connection: $connection = make_database_connection(); if (!$connection) die( No database connection! ); use_database_connection($connection); This example assumes that our imaginary function make_database_connection(), likemany PHP functions, returns a useful value if it succeeds, and a false value if it fails. An evenmore compact version of the preceding code takes advantage of the fact that orhas lowerprecedence than the =assignment operator. $connection = make_database_connection() or die( No database connection! ); use_database_connection($connection); This works because the oroperator short-circuits, and therefore the die()construct willonly be evaluated if the expression $connection = make_database_connection()has afalse value. Because the value of an assignment expression is the value assigned, this codeends up being equivalent to the earlier version. (Note that this would not work the same wayif we used ||instead of or, because ||has higher precedence than assignment, and so$connectionwould end up being assigned to the true-or-false result of the ||expression.) Before PHP5, the control structures we ve presented so far were really the only alternatives; control would flow from the first statement in a file to the last (possibly bounced around byfunction calls), unless prematurely terminated with die(). With exception-handling, PHP5introduces an alternate way to deal with problematic conditions, and one that is much moreflexible than die(). We treat exceptions briefly later in this chapter, and more thoroughly inChapter 31. In Table 6-3, we summarize all the control structures we ve seen thus far. Note08
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

101Chapter 6Control and FunctionsA note on (Post office web site) infinite loopsIf

Thursday, August 9th, 2007

101Chapter 6Control and FunctionsA note on infinite loopsIf you ve ever programmed in another language, you ve probably had the experience of acci- dentally creating an infinite loop (a looping construct whose exit test never becomes true andso never returns). The first thing to do when you realize this has happened is to interrupt theprogram, which will otherwise continue forever and use up a lot of CPU time. But what doesit mean to interrupt a PHP script? Is it sufficient to click the Stop button on your browser? As it turns out, the answer is dependent on some PHP configuration settings you can setthe PHP engine to ignore interruptions from the browser (like the result of clicking Stop) andalso to impose a time limit on script execution (so that forever will only be a short time). The default configuration for PHP is to ignore interruptions, but with a script time limit of 30seconds the time limitation means that you can afford to forget about infinite loops thatyou may have started. For more on the configuration of PHP, see Chapter 30. Alternate Control SyntaxesPHP offers another way to start and end the bodies of the if, switch, for, and whilecon- structs. It amounts to replacing the initial brace of the enclosed block with a colon and theclosing brace with a special ending statement for that construct (endif, endswitch, endfor, and endwhile). For example, the ifsyntax becomes: if (expression): statement1statement2.. endif; Or: if (expression): statement1statement2.. elseif(expression2): statement3.. else: statement4.. endif; Note that the elseand elseifbodies also begin with colons. The corresponding whilesyntax is: while (expression): statementendwhile; Which syntax you use is a matter of taste. The nonstandard syntax is in PHP largely used forhistorical reasons and for the comfort of people who are familiar with it from the early ver- sions of PHP. We will consistently use the standard syntax in the rest of this book. Cross- Reference08
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.