65Chapter 5Syntax and VariablesAssignment expressionsA very common kind (Free web space)

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.
); }
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Leave a Reply