<<

. 41
( 132 .)



>>

__construct(), but also destructor methods as well, named __destruct(). A
destructor function gets called when you destroy an object ” at the end of a script,
for instance. Or say you create an object inside of a procedural function. When a
function ends, all of its local variables go out of scope, so in a general sense the
memory assigned to them is released and the variables are destroyed. If you™ve
written a __destruct() function for your object, it would be called at that point.
You can use destructor functions to do any clean-up work that™s necessary: roll
back any open transactions, close database connections or logging files, and so on.

Exceptions
PHP 5 includes an exception scheme similar to that of the Java programming lan-
guage. In other words, it supports try/catch blocks, which were not supported in
earlier versions of the language.
You can, for example, define an exception class for later invocation, as in the
following example:

class DemoException
{
function __construct($exception)
{
$this->exception = $exception;
}

function Display()
{
print “DemoException: $this->exception\n”;
}
}

class DemoExceptionTosser extends DemoException
{
function __construct($exception)
{
$this->exception = $exception;
}
220 Part II: Working with PHP

function Display()
{
print “DemoExceptionTosser: $this->exception\n”;
}
}

try
{
throw new DemoExceptionTosser(˜Hello™);
}
catch (DemoException $exception)
{
$exception->Display();
}

This code works by attempting to execute what™s in the try block. When that
code uses the throw keyword to indirectly construct a DemoException object, the
exception is caught by the code in the catch block and subsequently printed out by
the Display() function.



Object-Oriented Code versus
Procedural Code
Here™s the million-dollar question: In your applications, should you use object-
oriented code or procedural code? This question can inspire heated debate. But
really such heated debate is unnecessary because there is a correct answer: It
depends upon the situation. If a given application can be designed to take advan-
tage of object orientation (in other words, if the problem at hand can be modeled as
a series of elements that interact), object orientation may be the way to go. And
since it™s possible to think of the entire world as a bunch of objects interacting with
each other, that™s a pretty strong possibility.
Object-oriented code comes with advantages and disadvantages. Weigh them
and decide for yourself if you should use classes or just functions.
The following are the advantages of object-oriented programming:

— In the long run (that is, across several projects), you can save time using
the object-oriented approach.
— You can make easily reusable pieces of code.

— You can make use of extensive class libraries available for free on the Web.
Chapter 7: Writing Organized and Readable Code 221

The following are the disadvantages of object-oriented programming:

— It™s slower than the procedural approach in the short term.

— The syntax can be confusing at first.

— Web programming does not make use of many of the advantages of
object-oriented code.
— If you™re using very large class libraries, you might experience a perfor-
mance reduction.



Comments
In any programming language, comments are essential ” not only to you as you™re
writing the code, but to those who come to the code after you. What may be crystal-
clear to you may be absolutely unreadable to others. Or, if you™ve had to do some-
thing particularly complex, you might find that you don™t even understand what you
were thinking if you come back to the code a couple of months after you wrote it.
In PHP you can indicate comments with two slashes (//), with a hash (#), or by
bracketing commented code with /* and */. This last method is particularly helpful
for multi-line comments.
Comment all of your functions, what they do, what they are expecting, and what
they return. Make sure to note any variables that might be tough to track.
As you look through the functions directory of the CD, you will see that every
function has an initial comment that mimics the style used in the PHP manual. For
example:

int fetch_record (string table_name [, mixed key [, mixed value]])

Then you provide some description as to what these arguments mean and the
significance of the return value. When writing the body of the function, you should
comment on anything that is not going to be intuitive to someone coming to the
script at a later date. If you have a series of functions that perform some complex
string handling or use lengthy regular expressions, make sure to note exactly what
those functions are intended to accomplish. For example, consider this line of code:

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

It isn™t especially difficult to figure out, but you can sure help the next person
coming to this line with a simple comment:

//get characters following the final dot
//and make lowercase
$file_ext = strtolower(substr($file, strrpos($file,”.”)));
222 Part II: Working with PHP

The other important thing to comment is the overall logic of pages, especially
long pages. Often a script behaves differently under different circumstances.
Variables passed from forms, errors, and other factors affect what portions of the
script run. At the top of the page, you can indicate what factors affect the page™s
logic and then, as you reach different if blocks, explain where the conditions are
coming from and what they mean.
For a brief example, take the confirm_delete.php page from Chapter 8, which
makes advantageous use of comments

/*
/*
********************************************************
*** This script from MySQL/PHP Database Applications ***
*** by Jay Greenspan and Brad Bulger ***
*** ***
*** You are free to reuse the material in this ***
*** script in any manner you see fit. There is ***
*** no need to ask for permission or provide ***
*** credit. ***
********************************************************
*/


/*
Application: Guestbook2k
Described in: Chapter 8
Name: confirm_delete.php
Purpose: Confirm, then perform, deletion of entries from the guestbook.


This script will be accessed in two circumstances:


- The ˜Delete Entries™ button on the edit.php page was pressed.
This should be the first time that the script is called. The ids
of the records to be deleted should be passed in via the entry_id[]
array.


- The ˜Confirm Delete™ button on this page was pressed. This confirms
the deletions and will run the delete queries against the database.


The $offset variable is preserved to allow navigation to other entriesin the
guestbook after or instead of confirming the deletion.


This script must be run by an authenticated user - i.e., only guestbook
administrators.


*/
Chapter 7: Writing Organized and Readable Code 223

// turn on PHP output buffering - only HTTP headers will be sent
// to the browser while this is on. it will prevent an accidental
// blank line or some such from breaking HTTP authentication.


ob_start();


require_once(˜header.php™);
guestbook_authenticate();


// turn off output buffering and send the accumulated output
// to the browser


ob_end_flush();


guestbook_start_page(˜Confirm Changes™);



$submit = (string)array_key_value($_POST,™submit™);


// if $entry_id hasn™t been passed in - because the user
// hit the ˜Delete™ button without checking off any
// entries, say - initialize it to an empty array.


$entry_id = (array)array_key_value($_POST,™entry_id™,array());


if ($submit == ˜Delete Entries™ && !empty($entry_id))
{
// presumably coming from edit.php. print out id values to be
// deleted and the ˜Confirm Delete™ submit button


// because the <form> tag contains no action attribute, it
// will submit back to this script


print “<form method=post>\n<ul>\n”;


foreach ((array)$entry_id as $value)
{
print <<<EOQ
<li>Delete entry #$value?
<input type=hidden name=”entry_id[]” value=”$value”>
EOQ;
}


print <<<EOQ
</ul>
224 Part II: Working with PHP

<br>
<input type=submit name=submit value=”Confirm Delete”>
<input type=hidden name=offset value=”$offset”>
</form>
EOQ;


}
else
{
// just in case this script is called directly or in some other
// unanticipated manner
print “<h4>No action to confirm</h4>\n”;
}


// display navigational links and end the page
nav($offset, ˜edit.php™);
guestbook_end_page();


We end this section on a word of caution: don™t over-comment. Commenting
every single line, or making the obvious even more obvious, is annoying. For
example, the following comments are completely unnecessary and only make a
script difficult to read:

//make string lowercase
$str = strtolower($str);
//increase $i by 1

<<

. 41
( 132 .)



>>