Archive for May, 2007

71Chapter 5Syntax and VariablesThis (Free web design) is identical to calling

Thursday, May 3rd, 2007

71Chapter 5Syntax and VariablesThis is identical to calling error_reporting()on the integer value of E_ALL, but is betterbecause the actual value of E_ALLmay change from one version of PHP to the next. It s also possible to create your own constants using the define()form, although this ismore unusual than referring to built-in constants. The code: define(MY_ANSWER, 42); would cause MY_ANSWERto evaluate to 42 everywhere it appears in your code. There is noway to change this assignment after it has been made, and like variables, constants that arenot part of PHP itself do not persist across pages unless they are explicitly passed to a newpage. Ultimately, you probably will not need to define constants very often, if ever. When cre- ated constants are used, they are generally most usefully defined in an external include fileand might be used for such information as a sales-tax rate or perhaps an exchange rate. Types in PHP: Don t Worry, Be HappyAll programming languages have some kind of type system, which specifies the different kindsof values that can appear in programs. These different types often correspond to different bit- level representations in computer memory, although in many cases programmers are insu- lated from having to think about (or being able to mess with) representations in terms of bits. PHP s type system is simple, streamlined, and flexible, and it insulates the programmer fromlow-level details. PHP makes it easy not to worry too much about typing of variables and val- ues, both because it does not require variables to be typed and because it handles a lot oftype conversions for you. No variable type declarationsAs you saw in Chapter 4, the type of a variable does not need to be declared in advance. Instead, the programmer can jump right ahead to assignment and let PHP take care of figuring out the type of the expression assigned: $first_number = 55.5; $second_number = Not a number at all ; Automatic type conversionPHP does a good job of automatically converting types when necessary. Like most other modern programming languages, PHP will do the right thing when, for example, doing mathwith mixed numerical types. The result of the expression$pi = 3 + 0.14159is a floating-point (double) number, with the integer 3implicitly converted into floating pointbefore the addition is performed. Types assigned by contextPHP goes further than most languages in performing automatic type conversions. Consider: $sub = substr(12345, 2, 2); print( sub is $sub
);
Note: If you are looking for high quality webhost to host and run your jsp application check Vision christian web host services

70Part IPHP: The Basicsaccomplish this, and the different (Geocities web hosting)

Wednesday, May 2nd, 2007

70Part IPHP: The Basicsaccomplish this, and the different techniques are a lot of what the rest of this book is about. For example, you can pass information from page to page using GETand POSTvariables(Chapter 7), store information persistently in a database (all of Part II of this book), associateit with a user s session using PHP s session mechanism (Chapter 24), or store it on a user shard disk via a cookie (Chapter 24). Functions and variable scopeExcept inside the body of a function, variable scope in PHP is quite simple: Within any givenexecution of a PHP file, just assign a variable, and its value will be there for you later. Wehaven t yet covered how to define your own functions, but it s worth a look-ahead note: Variables assigned within a function are localto that function, and unless you make a specialdeclaration in a function, that function won t have access to the global variables defined outside the function, even when they are defined in the same file. (We will discuss the scopeof variables in functions in depth when we cover function definitions in Chapter 6.) You can switch modes if you wantOne scoping question that we had the first time we saw PHP code was: Does variable scopepersist across tags? For example, we have a single file that looks like: ); ?> Should we expect our assignment to $usernameto survive through the second of the twoPHP-tagged areas? The answer is yes variables persist throughout a thread of PHP execu- tion (in other words, through the whole process of producing a Web page in response to auser s request). This is a single manifestation of a general PHP rule, which is that the onlyeffect of the tags is to let the PHP engine know whether you want your code to be interpretedas PHP or passed through untouched as HTML. You should feel free to use the tags to switchback and forth between modes whenever it is convenient. ConstantsIn addition to variables, which may be reassigned, PHP offers constants, which have a singlevalue throughout their lifetime. Constants do not have a $before their names, and by conven- tion the names of constants usually are in uppercase letters. Constants can contain onlyscalar values (numbers and string). Constants have global scope, so they are accessibleeverywhere in your scripts after they have been defined even inside functions. For example, the built-in PHP constant E_ALLrepresents a number that indicates to theerror_reporting()function that all errors and warnings should be reported. A call toerror_reporting()might look like this: error_reporting(E_ALL);
Note: If you are looking for reliable webhost to maintain and run your java application check Vision java hosting services

Web hosting companies - 69Chapter 5Syntax and Variablesprint( never_set print value: $never_set ); if

Wednesday, May 2nd, 2007

69Chapter 5Syntax and Variablesprint( never_set print value: $never_set
); if ($set_var == $never_set) print( set_var is equal to never_set!
); if (IsSet($set_var)) print( set_var is set.
); elseprint( set_var is not set.
); if (IsSet($never_set)) print( never_set is set.
); elseprint( never_set is not set. ); Oddly enough, this code will produce the following output: set_var print value: 0never_set print value: set_var is equal to never_set! set_var is set. never_set is not set. The variable $never_sethas never been assigned, so it produces an empty string when astring is expected (as in the printstatement) and a zero value when a number is expected(as in the comparison test that concludes that the two variables are the same). Still, IsSetcan tell the difference between $set_varand $never_set. Assigning a variable is not irrevocable the function unset()will restore a variable to anunassigned state (for example, unset($set_var);will make $set_varinto an unbound variable, regardless of its previous assignments). Variable scopeScopeis the technical term for the rules about when a name (for, say, a variable or function) has the same meaning in two different places and in what situations two names spelledexactly the same way can actually refer to different things. Any PHP variable not inside a function has globalscope and extends throughout a given thread of execution. In other words, if you assign a variable near the top of a PHP file, thevariable name has the same meaning for the rest of the file; and if it is not reassigned, it willhave the same value as the rest of your code executes (except inside the body of functions). The assignment of a variable will not affect the value of variables with the same name inother PHP files or even in repeated uses of the same file. For example, let s say that you havetwo files, startup.phpand next_thing.php, which are typically visited in that order by auser. Let s also say that near the top of startup.php, you have the line: $username = Jane Q. User ; which is executed only in certain situations. Now, you might hope that, after setting that variablein startup.php, it would also be preset automatically when the user visited next_thing.php, but no such luck. Each time a PHP page executes, it assigns and reassigns variables as it goes, and those variables disappear at the end of a page s production. Assignments of variables in onefile do not affect variables of the same name in a different file or even in other requests for thesame file. Obviously, there are many situations in which you would like to hold onto information forlonger than it takes to generate a particular Web page. There are a variety of ways you can07
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

68Part IPHP: The BasicsIt s conceivable that you (Web hosting provider) will

Wednesday, May 2nd, 2007

68Part IPHP: The BasicsIt s conceivable that you will want to actually print the preceding math expression ratherthan evaluate it. You can force PHP to treat a mathematical variable assignment as a string by quoting the expression: $pi = 3 + 0.14159 ; Reassigning variablesThere is no interesting distinction in PHP between assigning a variable for the first time andchanging its value later. This is true even if the assigned values are of different types. Forexample, the following is perfectly legal: $my_num_var = This should be a number hope it s reassigned ; $my_num_var = 5; If the second statement immediately follows the first one, the first statement has essentiallyno effect. Unassigned variablesMany programming languages will object if you try to use a variable before it is assigned; others will let you use it, but if you do you may find yourself reading the random contents ofsome area of memory. In PHP, the default error-reporting setting allows you to use unassignedvariables without errors, and PHP ensures that they have reasonable default values. If you would like to be warned about variables that have not been assigned, you should changethe error-reporting level to E_ALL(the highest level possible) from the default level of errorreporting. You can do this either by including the statement error_reporting(E_ALL); at the top of a script or by changing your php.inifile to set the default level (see Chapters 30and 31). Default valuesVariables in PHP do not have intrinsic types a variable does not know in advance whetherit will be used to store a number or a string of characters. So how does it know what type ofdefault value to have when it hasn t yet been assigned? The answer is that, just as with assigned variables, the type of a variable is interpreteddepending on the context in which it is used. In a situation where a number is expected, anumber will be produced, and this works similarly with character strings. In any context thattreats a variable as a number, an unassigned variable will be evaluated as 0; in any contextthat expects a string value, an unassigned variable will be the empty string (the string that is zero characters long). Checking assignment with IsSetBecause variables do not have to be assigned before use, in some situations you can actuallyconvey information by selectively setting or not setting a variable! PHP provides a functioncalled IsSetthat tests a variable to see whether it has been assigned a value. As the following code illustrates, an unassigned variable is distinguishable even from a vari- able that has been given the default value: $set_var = 0; //set_var has a value//never_set does notprint( set_var print value: $set_var
); Cross- Reference07
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

Web design rates - 67Chapter 5Syntax and Variablesdifferent result if you take

Wednesday, May 2nd, 2007

67Chapter 5Syntax and Variablesdifferent result if you take a single-line comment and replace one of the spaces with an end-of-line character. A more accurate way of putting it is that, after the comments have beenstripped out of the code, PHP code is whitespace insensitive. VariablesThe main way to store information in the middle of a PHP program is by using a variable away to name and hang on to any value that you want to use later. Here are the most important things to know about variables in PHP (more detailed explana- tions will follow): .All variables in PHP are denoted with a leading dollar sign ($). .The value of a variable is the value of its most recent assignment. .Variables are assigned with the =operator, with the variable on the left-hand side andthe expression to be evaluated on the right. .Variables can, but do not need, to be declared before assignment. .Variables have no intrinsic type other than the type of their current value. .Variables used before they are assigned have default values. PHP variables are Perl-likeAll variables in PHP start with a leading $sign just like scalar variables in the Perl scriptinglanguage, and in other ways they have similar behavior (need no type declarations, may bereferred to before they are assigned, and so on). (Perl hackers may need to do no more thanskim the headings of this section, which is really for the rest of us.) After the initial $, variable names must be composed of letters (uppercase or lowercase), digits (0 9), and underscore characters (_). Furthermore, the first character after the $maynot be a number. Declaring variables (or not) This subheading is here simply because programmers from some other languages might belooking for it in languages such as C, C++, and Java, the programmer must declare the nameand type of any variable before making use of it. However in PHP, because types are associ- ated with values rather than variables, no such declaration is necessary the first step inusing a variable is to assign it a value. Assigning variablesVariable assignment is simple just write the variable name, and add a single equal sign (=); then add the expression that you want to assign to that variable: $pi = 3 + 0.14159; // approximatelyNote that what is assigned is the result of evaluating the expression, not the expression itself. After the preceding statement is evaluated, there is no way to tell that the value of $piwascreated by adding two numbers together.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision web design programs services

Adelphia web hosting - 66Part IPHP: The BasicsYou can put any kind

Tuesday, May 1st, 2007

66Part IPHP: The BasicsYou can put any kind of statement in a brace-enclosed block, including, say, an ifstatementthat itself has a brace-enclosed block. This means that ifstatements can have other ifstate- ments inside them. In fact, this kind of nesting can be done to an arbitrary number of levels. CommentsA commentis the portion of a program that exists only for the human reader. The very firstthing that a program executor does with program code is to strip out the comments, so theycannot have any effect on what the program does. Comments are invaluable in helping thenext person who reads your code figure out what you were thinking when you wrote it, evenwhen that person is yourself a week from now. PHP drew its inspiration from several different programming languages, most notably C, Perl, and Unix shell scripts. As a result, PHP supports styles of comments from all those languages, and those styles can be intermixed freely in PHP code. C-style multiline commentsThe multilinestyle of commenting is the same as in C: A comment starts with the characterpair /*and terminates with the character pair */. For example: /* This isa comment inPHP */ The most important thing to remember about multiline comments is that they cannot benested. You cannot put one comment inside another. If you try, the comment will be closed off by the first instance of the */character pair, and the rest of what was intended to be anenclosing comment will instead be interpreted as code, probably failing horribly. For example: /* This comment will /* fail horribly on thelast word of this */ sentence*/ This is an easy thing to do unintentionally, usually when you try to deactivate a block of com- mented code by commenting it out. Single-line comments: # and // In addition to the /*…*/multiple-line comments, PHP supports two different ways of com- menting to the end of a given line: one inherited from C++ and Java and the other from Perland shell scripts. The shell-script-style comment starts with a pound sign, whereas the C++ style comment starts with two forward slashes. Both of them cause the rest of the currentline to be treated as a comment, as in the following: # This is a comment, and# this is the second line of the comment// This is a comment too. Each style comments only// one line so the last word of this sentence will failhorribly. The very alert reader might argue that single-line comments are incompatible with what wesaid earlier about whitespace insensitivity. That would be correct you will get a very
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

65Chapter 5Syntax and (Bulletproof web design) VariablesAssignment expressionsA very common kind

Tuesday, May 1st, 2007

65Chapter 5Syntax and VariablesAssignment expressionsA very common kind of expression is the assignment, where a variable is set to equal theresult of evaluating some expression. These have the form of a variable name (which alwaysstarts with a $), followed by a single equal sign, followed by the expression to be evaluated. For example: $eight = 2 * (2 * 2) assigns the variable $eightthe value you would expect. An important thing to remember is that even assignment expressions are expressions and sohave values themselves! The value of an expression that assigns a variable is the same as thevalue assigned. This means that you can use assignment expressions in the middle of morecomplicated expressions. If you evaluate the statement: $ten = ($two = 2) + ($eight = 2 * (2 * 2)) each variable would be assigned a numerical value equal to its name. Reasons for expressions and statementsThere are usually only two reasons to write an expression in PHP: for its valueor for a sideeffect. The value of an expression is passed on to any more complicated expression thatincludes it; side effects are anything else that happens as a result of the evaluation. The mosttypical side effects involve assigning or changing a variable, printing something to the user sscreen, or making some other persistent change to the program s environment (such as interacting with a database). Although statements are expressions, they are not themselves included in more complicatedexpressions. This means that the only good reason for a statement is a side effect! It also meansthat it is possible to write legal (yet totally useless statements) such as the second of these: print( Hello ); // side effect is printing to screen2 * 3 + 4; // useless - no side effect$value_num = 3 * 4 + 5; // side effect is assignmentstore_in_database(49.5); // side effect to DBBraces make blocksAlthough statements cannot be combined like expressions, you can always put a sequence ofstatements anywhere a statement can go by enclosing them in a set of curly braces. For example, the ifconstruct in PHP has a test (in parentheses) followed by the statementthat should be executed if the test is true. If you want more than one statement to be exe- cuted when the test is true, you can use a brace-enclosed sequence instead. The followingpieces of code (which simply print a reassuring statement that it is still true that 1 + 2 is equal to 3) are equivalent: if (3 == 2 + 1) print( Good - I haven t totally lost my mind.
); if (3 == 2 + 1) { print( Good - I haven t totally ); print( lost my mind.
); }
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

Adelphia web hosting - 64Part IPHP: The BasicsThe particular ways that operators

Tuesday, May 1st, 2007

64Part IPHP: The BasicsThe particular ways that operators group expressions are called precedencerules opera- tors that have higher precedence win in grabbing the expressions around them. If you want, you can memorize the rules, such as the fact that *always has higher precedence than +. Or you can just use the following cardinal rule: When in doubt, use parentheses to groupexpressions. For example: $result1 = 2 + 3 * 4 + 5; // is equal to 19$result2 = (2 + 3) * (4 + 5); // is equal to 45Operator precedence rules remove much of the ambiguity about how subexpressions areassociated. But what about when two operators have the same precedence? Consider thisexpression: $how_much = 3.0 / 4.0 / 5.0; Whether this is equal to 0.15 or 3.75 depends on which division operator gets to grab thenumber 4.0first. There is an exhaustive list of rules of associativity in the online manual, butthe rule to remember is that associativity is usually left-before-right that is, the precedingexpression would evaluate to 0.15, because the leftmost of the two division operators winsthe dispute over precedence. The final wrinkle is order of evaluation, which is not quite the same thing as associativity. Forexample, look at the arithmetic expression: 3 * 4 + 5 * 6We know that the multiplications will happen before the additions, but that is not the sameasknowing which multiplication PHP will perform first. In general, you need not worry aboutevaluation order, because in almost all cases it will not affect the result. You can constructweird examples where the result does depend on order of evaluation, usually by makingassignments in subexpressions that are used in other parts of the expression. For example: $huh = ($this = $that + 5) + ($that = $this + 3); // BADBut don t do this, okay? PHP may or may not have a predictable order of evaluation of expres- sions, but you shouldn t depend on it so we re not going to tell you! (The one legitimate useof relying on left-to-right evaluation order is in short-circuiting Boolean expressions, whichwe cover in Chapter 6.) Expressions and typesUsually, the programmer is careful to match the types of expressions with the operators andfunctions that combine them. Common expressions are mathematical(with mathematicaloperators combining numbers) or Boolean(combining true-or-false statements with ands andors) or string expressions(with operators and functions constructing strings of characters). As with the rest of PHP, however, the treatment of types is surprisingly forgiving. Consider thefollowing expression, which deliberately mixes the types of subexpressions in an inappropri- ate way: 2 + 2 * nonsense + TRUERather than produce an error, this evaluates to the number 3. (You can take this as a puzzlefor now, but we will explain how such a thing can happen in the Types in PHP section of this chapter.)
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check Vision professional web hosting services

Web hosting reviews - 63Chapter 5Syntax and VariablesThe different capitalization schemes make

Tuesday, May 1st, 2007

63Chapter 5Syntax and VariablesThe different capitalization schemes make for different variables. (Surprisingly, under thedefault settings for error reporting, code like this fragment will not produce a PHP error seethe section Unassigned variables, later in this chapter.) On the other hand, unlike in C, function names are notcase sensitive, and neither are thebasic language constructs (if, then, else, while, and the like). Statements are expressions terminated by semicolonsA statementin PHP is any expressionthat is followed by a semicolon (;). If expressions corre- spond to phrases, statements correspond to entire sentences, and the semicolon is the fullstop at the end. Any sequence of valid PHP statements that is enclosed by the PHP tags is avalid PHP program. Here is a typical statement in PHP, which in this case assigns a string ofcharacters to a variable called $greeting: $greeting = Welcome to PHP! ; The rest of this subsection is about how such statements are built from smaller componentsand how the PHP interpreter handles the evaluation of statements. (If you already feel com- fortable with statements and expressions, feel free to skip ahead.) Expressions are combinations of tokensThe smallest building blocks of PHP are the indivisible tokens, such as numbers (3.14159), strings ( two ), variables ($two), constants (TRUE), and the special words that make up thesyntax of PHP itself (if, else, and so forth). These are separated from each other by whites- pace and by other special characters such as parentheses and braces. The next most complex building block in PHP is the expression, which is any combination of tokens that has a value. A single number is an expression, as is a single variable. Simpleexpressions can also be combined to make more complicated expressions, usually either by putting an operatorin between (for example, 2+(2+2)), or by using them as input to afunction call (for example, pow(2*3,3*2)). Operators that take two inputs go in betweentheir inputs, whereas functions take their inputs in parentheses immediately after theirnames, with the inputs (known as arguments) separated by commas. Expressions are evaluatedWhenever the PHP interpreter encounters an expression in code, that expression is immedi- ately evaluated. This means that PHP calculates values for the smallest elements of theexpression and successively combines those values connected by operators or functions, until it has produced an entire value for the expression. For example, successive steps in animaginary evaluation process might look like: $result = 2 * 2 + 3 * 3 + 5; (= 4 + 3 * 3 + 5) //imaginary evaluation steps(= 4 + 9 + 5) (= 13 + 5) (= 18) with the result that the number 18 is stored in the variable $result. Precedence, associativity, and evaluation orderThere are two kinds of freedom PHP has in expression evaluation: how it groups or associatessubexpressions and the order in which it evaluates them. For example, in the evaluation pro- cess just shown, multiplications were associated more tightly than additions, which affectsthe end result.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services