. 37
( 132 .)


the characters following the dot. Finally, that string is set in lowercase characters.
This code can be written on one line, but as you can see, it becomes rather diffi-
cult to read:

$file_ext = strtolower(substr($file, strrpos($file,”.”)));

Or maybe you find this easier to read. A lot of things we talk about in this
chapter are matters of personal preference. The important thing is that you
spend a lot of time considering how to make your code as readable as possi-
ble. On the other hand, if you plan to share your code with others (especially
via public repositories like SourceForge), you should adhere to style conven-
tions. There doesn™t appear to be an official (or generally recognized) docu-
ment that describes PHP-coding style conventions. The PEAR folks have a
style guide you might want to peruse, at http://pear.php.net/

In the first example of this code, it™s much easier to see what each of the closing
parentheses relates to, and you can more quickly get an idea of what the code
accomplishes and how.

You might be tempted to write the preceding code using temporary assign-
ments to variables.That would look something like this:
$file_ext = strrpos($file, “.”);
$ext_letters = substr($file, $file_ext);
$lower_ext_letters = strtolower($ext_letters);
But this code is slower at execution time (not to mention at coding time),
though a code optimizer could reduce the problem. Variable assignments
do take time, and in a short piece of code where they aren™t necessary, stay
away from temporary-variable assignment.That said, you should avoid sacri-
ficing readability. In some places temporary variables can help make code
much easier to read. And there are circumstances when using a temporary
variable speeds up your code ” by avoiding repetition of a function call
whose results aren™t going to change, for example:
$len = count($array);
for ($i = 0; $i < $len; $i++)
196 Part II: Working with PHP

In neither case is the speed difference phenomenal. So, as usual, it ends up
being a question of what makes the most sense for you.

SQL statements
In Web-database applications, SQL statements are interspersed throughout PHP
code. Usually PHP variables are included within SQL statements to get specific
results based on variable data. Indenting SQL statements helps keep the code read-
able and maintainable. In the following example we show you a few examples of
SQL statements of various types. You can see many examples of these in the appli-
cations in Parts III and IV of this book.

//2 table select
$query = “select n.fname, n.lname
, c.co_name, c. co_address, c.co_zip
from names n, companies c
where n.name_id = $name_id
and n.co_id = $c.co_id

//update query in heredoc style
$query = <<<EOQ
update products
set product = ˜$product™
, description = ˜$cleandsc™
, price = $nullprice
, image_src = $nullimage_src
where product_id = $product_id

//insert query
$query = “insert into products (category_id, product)
values ($category_id, ˜$product™)

We™ve heard stories of database engines refusing to process queries that,
like the ones preceding, have newlines in them. This issue is not a problem
with MySQL and won™t be a problem with most database engines. However,
Chapter 7: Writing Organized and Readable Code 197

there are other perfectly acceptable ways to write queries that do not put
newlines in the queries, yet show indenting to the reader. Here are a couple
of examples using the concatenation operators:
$query = “select col_1, col2 “;
$query .= “ from table_1, table_2 “;
$query .= “ where col_1 = $var”;
$query = “select col_1, col_2 “
. “ from table_1, table_2 “
. “ where col_1 = $var”
Choose whichever you like best.

Every language has a facility for including external files. PHP has four commands
that enable you to do this. Before we get to those, we briefly discuss why includes
are so critical for writing organized and readable code. And we start with a very
common example.
In most Web sites, header information varies little from page to page. There are
opening tags (<HTML>, <HEAD>, and so on) and perhaps some navigation informa-
tion. The following is a typical HTML-page header:

<TITLE>My Page Name</TITLE>
<body bgcolor=”#FFFFF” link=”#8E0402” vlink=”#20297C”>

It is an absolute waste to type this text into every file within a Web site.
Moreover, it can be a real pain. Suppose you want to change the bgcolor attribute
of the <body> tag throughout the site. If this information were hard-coded in every
file, you would have no choice but to either go into each file individually and make
the change or write a script to do it for you.
You are far better off keeping all of this information in a single file (maybe
called header.php) and then using a command that spits the contents of that file
into the file being accessed. For this, you can use one of the PHP functions dis-
cussed in the next section. For this example we use include().
198 Part II: Working with PHP

You might want to give your include files a distinct extension ” .inc is a typ-
ical choice. One advantage of this approach is that the files can™t be run
directly from a browser, since the Web server is (usually) not configured to
recognize .inc as a PHP file. You can also store your include files outside of
your Web server™s document path for even more security (since some
servers respond to unknown extensions by printing out the file ” oops,
there™s your source code.)

Suppose you have two files, header.php and index.php. (Notice that we have
made an important change in header.php: The <TITLE> tags now contain a PHP

<TITLE> <?php echo $page_title; ?> </TITLE>
<body bgcolor=”#FFFFF” link=”#8E0402” vlink=”#20297C”>

You may have seen code like the above written like this:
<TITLE> <?= $page_title ?> </TITLE>
These “short tags” involve less typing, it™s true, but whether or not they work
is dependent on how PHP is configured. They™re likely to be disabled by
default, now or in future releases, so you should avoid using them.

Now for the index.php file:


$page_title = “Welcome to My Site”;

echo “Here are the contents of my PHP pages. Anything could be


Notice that the variable $page_title is visible to the file pulled in by the
include statement. When index.php is served, the resulting HTML page will be as
Chapter 7: Writing Organized and Readable Code 199

<TITLE> Welcome to My Site </TITLE>
<body bgcolor=”#FFFFF” link=”#8E0402” vlink=”#20297C”>

Keep any code, whether HMTL or PHP, that is needed in a variety of pages within
include files. Header and footer information, database-connection code, and pages
that contain functions or classes are all good candidates for includes.

At the start of an included file PHP reverts to HTML mode. If code within the
file needs to be parsed as PHP, you must first indicate that with the <?php

PHP contain a variety of commands that do slightly different things with
included files. We look at these commands in the following sections.

include() and require()
These commands are very similar and can usually be used interchangeably.
However, you should know what distinguishes the two, because at times using the
wrong one can cause problems.
The primary difference is indicated by the names. The require() command fails
with a fatal error if it can™t find the file it is trying to import; the file is “required”
to continue. The include() command, on the other hand, issues a non-fatal error
(which you can block with the @ operator) only if it can™t find the file, and PHP
continues processing your script.

include_once() and require_once()
In addition to include() and require(), PHP provides include_once() and
require_once(). These are provided to keep you, the developer, from stepping on
your own toes. As you might expect, they keep you from including the same file
twice, which, were it possible, could cause some problems when it comes to calling
user-defined functions.
For example, suppose you have a file that contains a function, but that the func-
tion relies on another function from an outside file. Your file would contain lines
like these:

require ˜helpful_file.php™;
function short_function()
200 Part II: Working with PHP


Suppose you give the name short_function.php to the file containing the preced-
ing lines. Later, if you try to include both short_function.php and helpful_file.php in
a third file, you™ll have a problem. The second time that helpful_file.php gets
included, it will try to redeclare functions that have already been declared once.
PHP will not let you do this and will spit out an error. So in cases like this use
include_once() or require_once(). Note that if files are included more than
once you might also have a problem dealing with variables that inadvertently over-
write each other.

User-Defined Functions
Chapter 6 shows many of the functions built into the PHP processing engine. If you
are a humble person and look at Appendix F or visit the online PHP manual, you
should be duly impressed by the quantity and power of PHP™s built-in functions.
But it isn™t enough ” and no matter how much work the able developers put into the
language, it never will be enough. That is because every developer on the planet
has unique needs. You need to accomplish specific tasks, and you need to do it in
ways that fit your own styles and predilections.
User-defined functions enable you to create blocks of code that achieve specific
tasks. The great thing about user-defined functions is that the code becomes
reusable. Any piece of code that you find yourself writing over and over should be
committed to a function. This saves you time in the long run.

In the applications presented in this book nearly all of the code is within
functions. The files that you see in your browser typically result from a num-
ber of function calls.This approach helps to keep things readable.

Function basics
You can start by writing a simple function that writes out the start of an HTML

function start_table()
echo “<table border=1>\n”;
Chapter 7: Writing Organized and Readable Code 201

To call this function within your PHP page, you access it just like a built-in PHP


. 37
( 132 .)