Languages - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Languages arrow Page 2 - Five Things You Didn't Know You Could Do with PHP
Five Things You Didn't Know You Could Do with PHP
By Larry Ullman

Rate This Article: Add This Article To:

Five Things You Didn't Know You Could Do with PHP - ' Tips 1 '
( Page 2 of 3 )

- 3">

When I began programming with PHP back in 1999, I felt that I'd discovered the perfect tool for quickly developing dynamic Web sites. At that time, the language's features and list of functions were both relatively modest. Over the years, the language itself, the extensions it supports, and its overall popularity have all dramatically increased. Unfortunately, it's also become more and more difficult for even the most attentive programmer to keep up. So, if you haven't caught all the new additions or discovered every useful function, start by checking out this list of the Five Things You Didn't Know You Could Do with PHP!

The first two ideas I discuss take what should be familiar code and use it in novel ways. The third example shows how to more easily debug and improve the professionalism of your sites through just a few lines of code. After that, a definite "I didn't know that existed!" function is given its due. The final item is a quick introduction to an interesting thing you can now do with PHP (not to ruin the ending for you, but PHP still can't mow your lawn). Naturally, see your friendly neighborhood PHP manual for more information about any of the functions covered.

ADVERTISEMENT

1. Test for a Range of Values using a Switch

The switch conditional is a great control structure, but the situations in which you can use it are limited. The switch is normally used to test if a variable is equal to a certain value, like so:

<?php
switch ($grade) {
	case 'A':
		echo 'Excellent!';
		break;
	case 'B':
		echo 'Nice job.';
		break;
	case 'C':
		echo 'Hit those books.';
		break;
}
?>

But did you know that the switch can also be used to test against ranges of options? I didn't either, until recently.

The trick to this use of switch is not to test a variable against a value, but rather test various conditions against the boolean TRUE:

<?php
switch (TRUE) {
	case ($age < 16):
		echo 'You cannot drive.';
		break;
	case ($age < 18):
		echo 'You cannot vote.';
		break;
	case ($age < 21):
		echo 'You cannot drink.';
		break;
	case ($age > 65):
		echo 'You should be retired.';
		break;
	default:
		echo 'Work, work, work...';
		break;
}
?>

Once you comprehend the logic, you can easily change the particulars for many other situations. Considering this, you might start rethinking just how useful the switch conditional can be.

2. Have print_r() Return Its Results Instead of Printing Them

Hopefully, you're familiar with print_r() already: this function merely prints out a variable's type and value information. While that may not seem like much, it's an immensely useful debugging tool. A simple example is:

<?php
$albums = array ('The Bends', 'OK Computer', 'Kid A');
print_r ($albums);
?>
which results in
<?php
Array (  [0] => The Bends  [1] => OK Computer  [2] => Kid A )
?>

As of PHP version 4.3 — a major upgrade to the language — you also have the option of capturing print_r()'s output. The function takes a second, optional parameter for this purpose. Using the previously defined array, just do this:

<?php
$capture = print_r ($albums, 1);
?>

Well, you could use it when you...

3. Handle Errors Your Way

The error reporting built into PHP is crude, at best. Be it a parse error, the infamous "headers already sent," or a "call to undefined function," what you'll see is the error type and filename in bold, some technical jargon, and a line number that may or may not be correct.

But you don't have to rely upon PHP's error handling style. For a while now, PHP has allowed you to define your own error handler, such as:

<?php
function my_handler ($number, $message, $file, $line) {
	// Match the formatting, CSS, etc., for your site's style!
	echo '

The following error occurred, allegedly on line ' . $line . ' of file ' . $file . ': ' . $message . '

'; echo '

The existing variables are:

' . print_r($GLOBALS, 1) . '

'; } ?>

Then you tell PHP to use your handler and not the default one by calling the set_error_handler() function.

<?php
set_error_handler('my_handler');
?>

From this point in your script forward, most errors will be handled by your function (there are some exceptions, including parse errors, which will still be handled the old way). With my example, the message is printed out with a little HTML formatting and, more importantly, all of the existing variables are printed within <pre> tags. This image shows how a division by zero error would be handled (in a real PHP script, there would be variables with actual values):

You might be thinking that I didn't really do anything novel with print_r() in my error handler. True, but I could just as easily build up a detailed error message that is then e-mailed to me should a problem occur on a live site (when you shouldn't display this information to the site's user).

Just in case that technique is a bit of a yawner to you, I'll also mention this: Along with the many new features in PHP 5, another method of error handling has been introduced, in keeping with C++/Java/C# style. This format uses the try-catch syntax:

<?php
try {
	if (!@mysql_connect('localhost', 'username', 'password'))
          throw new Exception (mysql_error());
} catch (Exception $e) {
	echo 'Could not connect to the database because: ' . $e->getMessage();
}
?>

Of course that's just a basic example; there's a lot more than you can do with this method of error handling. In particular, if you're comfortable with object oriented programming (OOP), you can define and use your own Exception class. Or you can have multiple catch statements, each catching a different type of exception.



 
 
>>> More Languages Articles          >>> More By Larry Ullman
 



Microsoft's Future: A Chat With Their CTO, Barry Briggs

Play Video >

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.