Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

The die statement is similar to exit, except that it may be followed by an expression that
will be sent to the browser just before aborting the script. Using the fact that
subexpressions in an if statement are evaluated left to right and only as necessary, the
idiom in Listing 3.11 is allowed. Notice the parentheses around the string to be printed
when the open fails. They are required.


Listing 3.11 Idiom for Using the die Statement


$fp = fopen("somefile.txt", "r") OR die("Unable to open file");


You will learn about the more traditional use of the return statement in Chapter 4, but
there is an unusual use of return offered by PHP when a script uses the include
function, described in Chapter 7. If called outside of a function, the return statement
stops execution of the current script and returns control to the script that made a call to
include. That is, when a script uses the include function, the included script may return
prematurely. If you use return in a script that was not invoked by include, the script
will simply terminate as if exit were used.


I admit this is a strange concept, and it probably deserves to have its own name instead of
sharing one with the statement for returning from functions. On the other hand, in certain
special cases, it allows for tidy code. One example is to avoid including a file twice, as
described in Chapter 20.


Evaluation of Boolean Expressions


The conditional statements in this chapter may be compound expressions, of course. PHP
will evaluate an expression only to the point of determining its ultimate value. The classic
situation is an expression that uses the or operator. PHP first evaluates the left side of the
or operator. If this subexpression is true, then there is no need to proceed. The entire
expression will be true. This can lead to unexpected functionality if you are embedding
function calls or assignment statements in your boolean expressions, but this isn't a good
idea anyway. However, there are ways to take advantage of this behavior. An example is
testing for something that should be true and calling an error-handling routine on the right
side of an or statement.

Free download pdf