Creating a custom error handler in PHP

To get the terminology straight, we talk about errors being “triggered”, whereas exceptions are “thrown”. The ability to throw and catch exceptions is new to PHP 5, but error handling has been around since PHP 4. In other object-oriented languages, there isn’t really a meaningful difference between errors and exceptions, but the distinction is very important in PHP. Errors can either be catchable or uncatchable, depending on how they’re triggered. Although you can trigger custom errors within your code if the need arises, errors are more commonly triggered by the parser or the PHP engine itself. Exceptions, on the other hand, are always thrown by actual PHP code, and not the underlying engine.

Let’s look at errors that can’t be caught. Parsing errors, the sort that happen when we forget to end a line with a semicolon or put one too many or few braces into our code, these aren’t going to trigger your custom handler function. The code just won’t work. In addition, errors that are thrown by the core, such as memory errors, or errors that can occur during startup, can’t be caught either. And lastly there are some errors, the ones of type ‘E_ERROR’ that just can’t be caught.

In order to handle errors, first you’ll need to create an error-handler function. The function takes 5 arguments, of which 2 are required and the rest are optional.

{show function syntax}

If you want the internal error handler to take over, for instance if your error handler is built to deal with just a few very particular cases, and based on the arguments passed, it’s been called for something different, then just return ‘false’. The internal handler will take over and execution will proceed as if your handler function weren’t there.

Here’s an example error handler:

{code sample}

The biggest change in custom error handling with PHP 5 is that you can now specify the type of error your handler function is intended to deal with, as opposed to just a catch-all for any error that a handler can deal with. This is helpful for dealing with the fact that, once you set a custom error-handler, the error_reporting setting inside php.ini will be ignored, and the custom function will be called for any reportable error type except E_STRICT. However, in PHP 6, E_STRICT will be included by default as well.

Even though the value of the error_reporting configuration isn’t checked before calling a custom error handler, you can still check the setting by calling error_reporting() with no arguments, and then have your own error handler function act appropriately based on that setting. On a related note, if the error-suppression character ‘@’ is placed at the beginning of the statement which triggered the actual error, the value of error_reporting will be 0 (or E_NONE) when checked.

Here’s a custom error_handler that takes the reporting level into consideration:

{code sample}

If you want to have an error handler that will handle any catchable errors in your code, you’ll need to set it near the beginning of your script. Up until the set_error_handler function is called, the default is the only one that gets called.

Let’s look at how this actually works. The following code will trigger an error because … … With the default error handler, the script will output this fairly unhelpful message {show broken page}.

Now, if we instead register this custom error handler function we looked at before

{show code example}

what we get instead is {show helpful error report}

A handy corollary to creating a custom error-handler function is the ability to trigger your own errors in your code. This capability is far less important in PHP 5 with the advent of exception-handling, but it’s still worth looking at.

The syntax is very simple. You just call ‘trigger_error’ with a message and, optionally, an error level. By default, it uses ‘E_USER_NOTICE’.

Here’s the previous example, but using ‘trigger_error’ instead of causing an error normally.

{code sample}

{show output}

Now, if you use exceptions in your code, and somehow have an exception that isn’t caught in a catch block somewhere, this also causes a catchable fatal error. However, rather than rely on setting a custom error handler, since exceptions provide different, and potentially useful debugging information, PHP allows you to set a custom exception handler that only gets called when an exception goes uncaught.

It has a pretty similar syntax to set_error_handler, except that the exception-handler function takes different arguments. Here’s how the function syntax is defined:

{code sample}

And here’s an example of using the custom handler to deal with an uncaught exception:

{code sample}

{show output}

January 16 2010 | Schmategories | Comments Off on Creating a custom error handler in PHP

A primer on good code commenting

Code is great, but comments are better. If code is what tells a computer what to do, then comments are how you communicate your intent. If the logic for a function is very clearly communicated in the comments, it can be translated by another programmer into any other programming language. If a piece of code is well-commented throughout, then even without knowing all there is to know about the language or the rest of the classes being accessed at any given point, you can figure out what the code is doing. When you need to bring a new developer up to speed on your project, a huge factor in how quickly they’ll become useful is how well your project is commented.

I’m going to assume that you’re already familiar with how to create a comment, so this video is going to focus more on what and where to comment.

Probably the first and most important thing to comment are your functions and methods. These comments can significantly illuminate your API, and that can make it easier to find and re-use existing code or bring new developers up to speed.

PHP has an excellent support community dedicated to it, and out of that community came phpDocumentor – a handy free tool that will take your project and automatically generate an API for you. It will use your comments to flesh out that API, but only if you use a style of commenting known as “javadoc” or “doc-block”. Even without using this tool however, it’s a great convention to follow. Zend Studio, which I use for my own coding environment, automatically recognizes this style of comments and will assist in their creation.

The basic syntax of javadoc looks like this: {show prepared code segment with comment}

Notice that the first line contains a slash followed by 2 asterisks, and each line starts with an asterisk. The description of whatever is being commented is the first thing in the block. After that, you can use tags preceded by @ symbols to provide very specific information that programs such as phpDocumentor use.

There are a limited number of elements where phpDocumentor looks for and parses javadoc-style comments. I suggest you make a habit of placing these comments at the top of all of them. These include files, functions, defines and includes, as well as any global variables. And assuming your project is object-oriented, you should also place these comments above your class definitions, their methods, and their properties.

When documenting a function, as is the case here, your most important tags are ‘@param’ and ‘@return’. ‘@param’ tells the name and expected value type for each variable passed to the function (this information can also be gleaned to some extent from type-hinting, but not as broadly since as of PHP 5 type-hinting only includes null, array, and object types). ‘@return’ provides information about the type of value returned. In addition to those two, if your method can throw an exception, you should include a tag for ‘@throws’ for every type of exception your function might throw – the syntax is “@throws ExceptionType – conditions which will cause this exception to be thrown”.

Now in addition to those tags, javadoc officially recognizes many more. I won’t discuss all of them – there’s an exhaustive tutorial available online that I’ll point you to in a moment. But I will take you through the ones I find most helpful most often.

To reference another method elsewhere in your code, you can use ‘@see’. And in phpDocumentor this is really great, because if it recognizes what you’re linking to, it will actually create a hyperlink to the documentation of that other portion of your code. So for instance ‘@see GoToClass’ would create a link to the documentation for a class called ‘GoToClass’ if one exists in your project. And of course, it’s useful even if you don’t use phpDocumentor because it lets your reader know what other portions of the code use or are used by the thing you’re documenting.

When a project has lots of authors, it’s a very good idea to include a tag ‘@author’ in each of your contributions. Later, if someone has a question about how it works, they can see who wrote it and ask them to explain it.

At the beginning of each file, you can place a javadoc comment as well. In the automatically generated documentation, file or page-level comments have its own section. When you use it, you must include the ‘@package’ tag. The value in @package will specify a particular group of files that all relate to one another, and all appear within the navigation generated by the documentor for that package.

When you have to stop working on something before it’s finished, there’s a tag for that too. Use ‘@todo’ followed by a description of what still has to be written.

There are currently about 30 different tags recognized by phpDocumentor, and most other javadoc parsers will recognize them as well. You can learn about all of them by going to the phpdoc manual online.

Javadoc comments placed above your files, classes, functions, methods, and properties will really liven up your API if you generate one. And even if you don’t it’s going to make your code much easier to understand. But the other important places to comment are anytime you do something where simply looking at the code, it would be difficult to figure out what’s going on. As a general guide, if you call a function defined elsewhere, include a short comment about what that function should do. That way, the person trying to work on it doesn’t need to go and hunt down its definition in a separate file. The same is true if you invoke one of the more obscure PHP functions. And if you simply need to perform a task that requires some tricky logic, or is unlike the way things are done elsewhere in the project, write a short comment explaining what you did.

Personally, I find the best way to write my scripts is to start by outlining my logic within comments before I ever write my code. Then, I just place my code within the lines of logic where I’ve described what needs to happen. It helps me ensure my logic is good before I even start the actual coding, and when I’m done, I just leave the outline there for documentation.

December 08 2009 | Schmategories | Comments Off on A primer on good code commenting

What's new in PHP 5.3 – Namespaces

PHP 5.3 included a couple of significant new features that are worth giving their own space to cover. These are “namespaces” and “late static bindings”. I’ll discuss late static bindings in the chapter on objects and classes, but in this video we’ll look at namespaces.

Something you will see fairly often in larger PHP applications is classes with names like: Doc_Event_Model_BuildHelper
This sort of name is common, and provides a couple handy features. For one, if it follows the typical convention, you know that within whatever directory classes are kept, there is probably a folder called ‘doc’ with a folder called ‘event’ with a folder called ‘model’ with a file called ‘BuildHelper.php’. And assuming it’s PHP 5 or later, then there is most likely an __autoload function that tells PHP which path to check when trying to load this class. The other useful trait is that it avoids naming collisions. In PHP, no 2 classes can have the same name (and neither can constants or functions).

The downside to this convention is that class names can get very long, and there isn’t a similar convention for constants or functions, which similarly can’t have more than one instance of the same name. As a result, large programs often won’t define functions or constants except as static methods or constants on these long-named classes. Namespaces give you an alternate way of relating the various parts of your code, and prevents naming collisions with unrelated components.

The most basic way to think about namespaces is to liken them to your file manager’s directory structure. If all of your files were in the same folder, then no 2 files could have the same name, and as you added files over time, the file names would need to get pretty long to avoid overwriting existing files. So instead, we can use directories to organize our files into smaller related groups. And when you need to refer to a file, you can use a relative path or an absolute path.

With namespaces, like directories, we arrange our code into related parts. When we refer to namespaced code, we also use absolute or relative names. To use the proper terminology, we refer to these names as either as ‘qualified’, ‘unqualified’, or ‘fully-qualified’.

For instance, in the namespace ‘Foo’, a call like ‘$a = new Bar()’ would actually attempt to create a new instance of ‘Foo\Bar’, meaning some class called “Bar” within the namespace “Foo”. And in this case, we would refer to “Bar” as an unqualified name, since it has no namespace qualifier preceding it.

On the other hand, a fully-qualified name is like an absolute path to a file in your directory. The system knows it’s fully-qualified because it begins with a “\” character. So, using the example above, we might write “$a = new \Foo\Bar()”. In both examples, PHP would interpret this as a call to create a new instance of the class “Bar” residing in the namespace “Foo”.

Another way to create a fully-qualified name is to use the special “namespace” keyword. In this context, it acts much like the “self” keyword for a class. We could change our code to “$a = new namespace\Bar()” and it would again do the same thing. The usefulness here is that you can write code that is totally agnostic about the actual namespace it resides in, so long as it does actually contain some class by the name of “Bar”.

A “qualified name” is analogous to a relative path to a file within a sub-folder. You can have sub-namespaces the same as you can have sub-folders. So, back to our previous example, suppose there was a sub-namespace within Foo called “AnotherFoo,” which also had a class called “Bar”. If we wanted to specify that we were using that class instead, we could write “$a = new AnotherFoo\Bar()”. Notice there’s no forward slash at the beginning of the class name. So, what we actually get, in terms of a fully-qualified name, would be \Foo\AnotherFoo\Bar.

PHP will convert unqualified and qualified names into fully-qualified names at compile time.

Now that we’ve explored terminology, let’s look at how we actually define our code within a namespace.

When you declare a namespace within a file, it must come at the very start of the file. The only exception PHP allows is a declare statement to identify the type of encoding for the file. Consider the following code:
<html>
<?php
namespace Joe {

}

this code throws a fatal error because of the line above the php tag.

However if this is how your file begins:
<?php
namespace Joe {

}

Then you’re fine.

When you declare a namespace, any files you include within that namespace will also be a part of it. If the file ‘mover.php’ contains the class ‘Mover’, then in the following code:

namespace Joe {
include(“mover.php”);

}

the fully-qualified name for the class Mover will actually be \Joe\Mover.

In the same way, if you include a file that also defines a namespace from within a namespace, then that included namespace is going to be a sub-namespace.

For instance, if the following lines begin a file included within the namespace declaration ‘A’

namespace B {

function do_something() {

}

}

then the fully-qualified call to that function would be \A\B\do_something().

To be really useful though, it would be nice to be able to avoid writing a number of separate ‘include’ calls, and simply use the power of PHP 5’s ‘__autoload’ capability. __autoload is a special global function that PHP calls when an unrecognized class is referred to, instead of simply throwing an error (a la PHP 4). This function attempts to include a file based on the name of the class, in hopes that the referenced class will be found there.

Creating a custom __autoload function will be discussed in a separate video, but one of the most wonderful things about PHP 5.3 is that most of us won’t need to write one – the default __autoload function included with SPL already understands namespaces.

To enable, just call ‘spl_autoload_register()’ without paramters. If you want to specify a certain directory containing your classes, use ‘set_include_path’ to ensure that the autoload function checks there. And you can make sure that php uses a specific extension, such as ‘.class.php’ by calling ‘spl_autoload_extensions()’. Check out this example:

set_include_path(get_include_path() . ‘/classes’);
spl_autoload_extensions(‘.class.php’);
spl_autoload_register();

Now, whenever the code tries calling a class that hasn’t been included yet, say ‘\Useful\Class\Test’, the code will look inside the folder ‘classes/Useful/Class’ for a file called ‘Test.class.php’. And if it finds it, and the file contains a definition for the class ‘Test’ within the namespace ‘\Useful\Class’, then the class will be used seamlessly, and no explicit include file will be necessary.

Now it’s true that you can write your own __autoload function to do the same exact thing, but the spl_autoload function, since it’s actually written in C and not PHP, is going to be slightly faster. My advice is, whenever possible, try to create your directory structure in such a way as to make use of this handy default behavior.

December 06 2009 | PHP tutorial scripts | Comments Off on What's new in PHP 5.3 – Namespaces

What was introduced in PHP 5

PHP 5 introduced a number of revolutionary features to the language that made it a much more elegant solution to many of the common programming challenges developers face. Object support went from something of a glorified after-thought to a truly compelling, modern approach. Several useful libraries and interfaces were added, and exception handling was finally given the attention many developers had longed for. Each of these are covered in their own chapters, but there were just a few other add-ons that, while too important not to cover, didn’t easily fit into more focused chapters.

Briefly, we’re going to look at three of these new features: type-hinting, objects being passed by reference, and indirect referencing.

Type hinting allows you to more precisely specify the types of arguments that should be passed into your function. In the definition, you can do something like:

function myFunction(MyClass $object) {
//do something with $object
}

This sets up a guarantee that when the function is run, $object will either be an instance of “MyClass”, an instance of a child class of MyClass type, or an instance of a class that implements an interface called MyClass. And this might be really important. Having it specified this way in the function definition will also ensure that anyone working on your code later will know that. In addition to class and interface names, you can also type-hint for arrays. The ‘null’ value is always allowed as a default:

function myFunction(MyClass $object = null) {
//if no argument is passed, or if a null is passed explicitly, this function will work
}

But you cannot have something like this:

function myFunction(MyClass $object = new MyClass()) {
//this code will not parse
}

Oddly enough though, you CAN do this:

function myFunction(array $array = array()) {
//this code is perfectly legit
}

And you cannot type-hint for scalars, like ‘int’, ‘float’, or ‘string’:

function myFunction(int $int) {
//won’t work in PHP 5 – maybe PHP 6 will allow?
}

However, there is one warning to bear in mind with this approach. If the argument is NOT an instance of MyClass (or a child, or an implementer) your script will trigger a catchable fatal error, not an exception. In order to deal with this type of fatal error, you need to create a global-scope function and use it as the argument in a call to ‘set_error_handler()’ to replace PHP’s default handler. We’ll take a closer look at creating custom error handlers in another video, but here’s some code we could use in this situation:

{@todo – write and test example error-handler code}

However, if you’d rather not deal with custom error handlers, there are other ways to ensure that your function is getting the variable type you expect, and still make it clear to those who follow what is expected. There is a special docblock comment tagline “@param”. If you use a development environment such as Zend Studio, or run phpDocumentor on your code, the argument requirement will be listed along with the function documentation. And if you want to halt execution when the wrong argument type is passed, you can test the type explicitly within your function and throw an exception that can be caught and handled properly. Here’s what that looks like in practice:

/**
* this function does something useful
* @param MyClass $object
*/
function myFunction($object) {
if(! $object instanceof MyClass) {
throw new InvalidArgumentException(‘$object must be an instance of MyClass’);
}
//do something
}

We’ll look more at docblock comments as well as phpDocumentor in another video. But suffice to say this approach will work in many of the situations when you might consider using type-hinting, and it can be made to work with multiple types and scalars. The disadvantage, of course, is somewhat longer code, and needing to ensure that your function is called within the scope of a matching try-catch block.

The “instanceof” keyword, by the way, is also new to PHP 5. It’s essentially an analog to the is_a() function that’s been around since PHP 4. Like type-hinting, it tests whether an object is an instance of, a child of, or an implementation of the class or interface name in the right-hand argument.

For a while, the PHP engineers had decided to deprecate “is_a()” in favor of the instanceof keyword, and in PHP 5 before 5.3, it would toss an E_STRICT warning. However, as of PHP 5.3 it is no longer deprecated. Both is_a() and instanceof are now considered equally valid.

Perhaps the most significant change between PHP 4 and 5 is the fact that objects are now passed by reference by default. The reason I say it’s the most significant isn’t because it completely revolutionizes the language – PHP 4 could pass objects by reference by using the ‘&’ in front of variables in a function definition, as in the example shown here:

function myFunction(&$obj) {
//In PHP 4, $obj is a reference to an object, rather than a copy of it
}

The reason it’s so significant is because, while the PHP engineers worked very hard to make sure almost all PHP 4 scripts would work the same under PHP 5, this is one area where they might not. Consider the following code:

class Account {
var $balance = 0;

static function addFunds($account, $amount) {
$account->balance += $amount;
}
}

$account = new Account();
Account::addFunds($account, 20);
echo $account->balance;

In PHP 5, the output will be ’20’, but in PHP 4, no change actually takes place to the $account object, so the output is ‘0’. Under PHP 4, the function gets a copy of the $account variable, rather than a reference to the original variable as it does in PHP 5. And in this example, obviously it’s the PHP 5 behavior that would be intended. But that’s not always the case.

Imagine that a PHP 4 script were written that takes an object and performs some action on it with the expectation that it NOT change the original object. Trying to run that same script in PHP 5 could result in very unexpected behavior. And indeed, if your old scripts break when running under PHP 5, there’s a good chance that this new behavior is behind it.

Now, because there are some situations where you want the ability to work on a copy of an object rather than the object itself, PHP 5 provides an easy mechanism for doing that.

$object = new MyClass(5, 5);
$copyOfObject = clone $object;

In this case, any properties set in $object will be set identically in $copyOfObject, so making changes to $copyOfObject won’t affect $object. In another video we look at how you can have more fine-grained control over exactly how an object is copied by defining the __clone() method in your class, but for most cases, the default behavior of ‘clone’ is sufficient.

The final addition to PHP 5 we’re going to look at is called “indirect referencing”. And it’s a great way to take many lines of code and turn them into just a few. Consider this example from a typical PHP 4 script:

$var1 = $object->var1;
$var2 = $var1->var2;

var1 is actually an object itself that also happens to be a property on $object, and var2 is a property of var1. In PHP 5 we can shorten this to just:

$var2 = $object->var1->var2;

In PHP 5, there is no need to actually declare temporary variables in these types of situations. The code above will simply get the first variable and then use it to get the subsequent variable. It works for functions and methods as well:

$var2 = $object->method1()->var2;
$var2 = myFunction()->var2;
$var8 = $object->var1->method2()->var3->method4()->method5()->var6->var7->var8;
//so long as an object is returned with each ‘get’ or method call (aside from the last), all these examples are valid!

Indirect referencing leads to a handy programming technique called “chaining”. The last example shows how it can drastically shorten code versus PHP 4.

There were a number of other important changes introduced in PHP 5, and several of those will be examined in the section on Object Oriented Programming, but this concludes the ones I wanted to look at here.

October 14 2009 | introduction and PHP tutorial scripts | Comments Off on What was introduced in PHP 5

Exception-handling with try-catch blocks

PHP 5 introduced something that programmers in other languages had come to rely on for exception handling. It’s called the try-catch block. In most languages that use the try-catch block, any time a run-time error occurs, it can be trapped inside a catch statement and dealt with in some manner appropriate for that particular situation. This is not the case in PHP 5.

Actual errors that the PHP engine generates aren’t considered exceptions the way they’re defined here, which is why it’s important to understand the difference between errors and exceptions. But if you want your code to generate and deal with procedural anomalies of any sort, or if you just want to halt execution without using a return statement, then exceptions are a fantastic tool to learn. PHP does provide a means for actual error-handling, but that topic is covered in another video.

So anyway, with the try-catch blocks, here is the basic syntax:

try {
//run some code
} catch(Exception $e) {
//do something
}

Basically, the code inside the try block runs, and if it causes an exception to be thrown, then execution of that block stops immediately, and the engine jumps into the catch block to begin execution. Exceptions are only thrown by actual PHP code. So your scripts and libraries may throw an exception, but if there’s an error within the PHP engine itself, the catch block won’t be triggered.

Take a look at the following example:

if($db->connect() === false) {
throw new Exception(‘could not connect to database’);
}

If this particular code is executed from within a try block, and the connect() method returns false, then the corresponding catch block will be called. It’s important to note that uncaught exceptions result in fatal errors, so don’t throw them unless you’re sure there’s a catch clause to deal with it. Alternately, if you want a last-resort catch clause, you can set a global exception handler. However, since the syntax for that is so similar to setting a custom error handler, I talk about that in the same video where I discuss setting custom error handlers.

The throw statement can act similar to a return in that it halts execution of a function (or at least, it will if it isn’t thrown within a try block), but instead of just returning to the point where that function was actually called, it continues up the stack until it finds a corresponding catch block.

Now, what I mean by corresponding catch block is one that matches the type of exception being thrown. The example above uses the basic class “Exception”, but that’s not the only option. PHP 5 provides several more specific Exception classes you can use, and it’s a simple matter to create your own. The catch block makes it clear what type of exception it can receive. Since all exceptions are based on the “Exception” class, a catch block like this:

catch(Exception $e)

will catch any type of exception thrown in its corresponding try block.

But supposing I wanted to handle different types of exceptions differently. A single try block can lead to multiple catch blocks:

try {
throw new UnexpectedValueException(‘unexpected!’);
} catch(InvalidArgumentException $i) {
echo ‘InvalidArgumentException: ‘ . $i->getMessage();
} catch(UnexpectedValueException $u) {
echo ‘UnexpectedValueException: ‘ . $u->getMessage();
} catch(Exception $e) {
echo ‘Exception: ‘ . $e->getMessage();
}

The code shown here will display “UnexpectedValueException: unexpected!” because the second catch block is the one that corresponds to the type of error thrown. However, since all exceptions are of the type “Exception” changing the code to the form shown below will change the output:

try {
throw new UnexpectedValueException(‘unexpected!’);
} catch(InvalidArgumentException $i) {
echo ‘InvalidArgumentException: ‘ . $i->getMessage();
} catch(Exception $e) {
echo ‘Exception: ‘ . $e->getMessage();
} catch(UnexpectedValueException $u) {
echo ‘UnexpectedValueException: ‘ . $u->getMessage();
}

This code will display “Exception: unexpected!”. That’s because PHP will go through each catch block in order until it finds one that matches, and then it will stop. Even though “catch(UnexpectedValueException $u)” is the BEST match, “catch(Exception $e)” is the FIRST match.

Alternately, the example below will simply cause a fatal error unless it’s called within the scope of a matching try-catch block higher up in the stack:

try {
throw new UnexpectedValueException(‘unexpected!’);
} catch(InvalidArgumentException $i) {
echo ‘InvalidArgumentException: ‘ . $i->getMessage();
}

Since the type of exception thrown doesn’t match any catch block.

In the above examples I used, InvalidArgumentException and UnexpectedValueException are actually built into PHP 5, along with several others. But inventing your own exception class is as simple as:

class MyNewException extends Exception { //no class code needed!
}

Include that class definition somewhere in your project space, and you can throw and catch MyNewException wherever you want. The name just helps differentiate exception types. This technique is useful for detecting when something unexpected has happened and dealing with it.

When catching an exception, the argument after the type of exception is a reference to the actual exception itself. In the case of:

try {
//do something
catch(Exception $e) {
//do something
}

“$e” is the specific object of the Exception class that was thrown and caught.

The exception class itself provides several methods you should know about. You can see more examples by searching php.net.

$e->getMessage();

Exceptions can be thrown with no arguments, but for debugging purposes, it’s usually helpful to include at least the first argument, a string, telling why the exception was thrown. For instance, if the script does this:
try {
throw new Exception(‘Go directly to the catch block’);
} catch(Exception $e) {
echo $e->getMessage();
}
the script will print “Go directly to the catch block”. Obviously, this isn’t a particularly helpful message, but you get the idea.

The second argument for an exception, if provided, is a code. Again, you can choose whatever you want, and calling “getCode()” will just return whatever you provided. Some programmers prefer to use numbers to classify their exceptions, since they can be a little less ambiguous than strings. And obviously, there’s no reason you can’t use both messages and codes in your exception. Here’s the syntax:

$e->getCode();

And an example:

define(‘EXAMPLE_EXCEPTION’, 55);
try {
throw new Exception(‘an example exception occurred’, EXAMPLE_EXCEPTION);
} catch(Exception $e) {
echo $e->getCode();
}

And this script would print “55”.

The final argument for creating an exception is another exception. The idea is that if an exception is caught in one catch block, and then a new one is thrown again, the newer exception can contain a reference to the old one. This isn’t something you see very often, but it’s easy enough to understand. Here’s another simple example:

try {
try {
throw new Exception(‘This is the way it is’);
} catch(Exception $e1) {
throw new Exception(‘Here is what I think’, null, $e1);
}
} catch(Exception $e2) {
$e1 = $e2->getPrevious();
echo $e2->getMessage() . ”
“;
echo $e1->getMessage();
}
And this code will print “Here is what I think” followed by “This is the way it is” on the line below.

In addition, the exception can return information about the stack at the time it was thrown. There are a couple different functions for this depending on whether you want the back trace as a string or an array, or whether you just need the specific line or file where the exception took place. Here they are very briefly:

$e->getTraceAsString();

returns the entire trace as a string

$e->getTrace();

returns an array where each line in the stack is a separate element

$e->getFile();

returns the path to the file where the exception was thrown

$e->getLine();

returns the line number where the exception was thrown

October 13 2009 | introduction and PHP tutorial scripts | Comments Off on Exception-handling with try-catch blocks

Introduction

PHP has become one of the most prominent web development languages in production today. Part of this is because it is so easy for someone to dabble with it and achieve immediate results. It takes very little expertise to incorporate PHP into an otherwise straightforward html page, and that makes it popular with many designers.

The fact that those first few steps are so easy helped the language achieve some of its initial adoption, but that’s only part of the reason it’s become so widespread. While a web designer might appreciate a simple way to rotate a banner ad, or change some style based on the date or time, a skilled web developer can actually power the entire website, from serving up content, to managing access permissions, and interacting with data from around the internet. PHP is a powerful language, and while that power can be dangerous, it can be incredibly freeing to a developer.

Most large websites, including heavyweights such as Google, Yahoo, Amazon, and Paypal, provide developers tools for interacting with them through their own PHP scripts.

Many websites – large and small – use PHP to power their content management system, or CMS.

And there are a number of open source projects, written in PHP, that harness the collective skill of thousands to create truly great software. My personal website, powered by WordPress, is one example of such an effort. Others you might be familiar with include Joomla, Drupal, and phpBB.

The goal of this training course will be to take you from a basic understanding of PHP to what can be called an advanced level. At this point, you should already be comfortable writing functions and classes, using the basic language constructs like loops and conditional statements, connecting your scripts with a database and interacting with the server’s filesystem. You should know some of the more common functions provided by PHP itself, and for the most part, you should be able to look at another developer’s PHP code and figure out what it does.

At an advanced level however, you’ll need to be aware of the various tools and libraries available to you as a developer and how to incorporate them. You’ll want to gain a deep understanding of how object-oriented programming should work in PHP, so you can put it to the best possible use in your scripts. And perhaps most important, you’ll need to learn how to secure your websites and web applications against all the ways someone might try to exploit them.

PHP has earned its place of prominence because of its ease of use, power, and scalability. It is well supported, and well documented, and is unlikely to lose its popularity within the foreseeable future.

October 13 2009 | introduction and PHP tutorial scripts | Comments Off on Introduction

New project and new direction

I work full-time now, and haven’t felt the need to update my portfolio regularly. That doesn’t mean I’ve forgotten it’s here – I do keep the hosting and domain registration fees paid. I just haven’t had a specific use for this blog for some time now.

However, that’s changed now. I’m very pleased to announce that I have a contract to create a series of advanced PHP video tutorials, and have been given a sufficiently flexible timeline that it shouldn’t interfere with my regular job.

Because of the NDA I signed, I can’t actually reveal what company I’m working with, but once the tutorial is finished and available for purchase, I will be promoting it here.

Now as far as the tie-in with the blog, I’ve decided that I’m going to share my research for each video by creating corresponding blog entries. The blog posts won’t include the videos themselves, but they will form the basis of the scripts I’ll use when I create them.

In time, there should be a lot of useful information on a variety of topics. Hopefully my visitors will find some of the articles useful, and may even be able to correct me if I make an error now and then.

It’s been a long time since I’ve had to research and write anything on that kind of schedule, and that’s in addition to my responsibilities at work and to my family. But I think I can handle it, because becoming a published author has been a dream of mine for a long time now, and nothing is so easy as doing work you love. Wish me luck!

October 12 2009 | Schmategories | Comments Off on New project and new direction

JQuery-UI Photo Cropping Tool

This was a cool little application I devised after one of my clients explained that he wanted the ability to have users upload a photo and have it automatically fit into a particular size.

Now, my first reaction could have been to simply use ImageMagick or the GD Library to simply create a thumbnail, but I’ve done that in the past and seen it stretch images in unexpected ways. He knew exactly the size he’d want his images resized to, and I didn’t want to force the users to submit pictures with a particular aspect ratio.

So, the solution I came up with, and am still pretty proud of, is a photo-cropper and resizer in one. It lets the user upload a photo, and then zoom in to a particular portion, crop it, and use it as their submission to the website. It uses javascript (jQuery flavor) to mimic the effect of selecting the target area, and then PHP on the backend does the actual resizing.

Try it out below. Your actual-size final result will appear beneath the button here on the screen. Due to limitations imposed by my server host however, large photos may not work. It wasn’t an issue for my client, since he has the luxury of a dedicated machine.


Download the source
(222 KB compressed with related graphics and script libraries)

October 21 2008 | Schmategories | Comments Off on JQuery-UI Photo Cropping Tool

Calculating the value of a single lottery ticket

Here’s a neat question – how much is a lottery ticket worth before the numbers are drawn?

The problem is a fun one for someone with a love of statistics, or someone who just wants to prove a point about why they never buy a lottery ticket. To answer it, I first make a few assumptions.

  1. The value of a future dollar is uncertain, so I will only base the value of winning a jackpot on the cash payment option, and not the annuity payments.
  2. Any prize over $5000 will automatically be taxed at a rate of 25% to federal and possibly some additional amount to state and local depending on the winner’s location. Hence, a jackpot-winning ticket is only worth at most 75% of the cash payment option after taxes.
  3. The more tickets that are purchased, the more likely it is that the jackpot will be shared if won, and so the number of tickets purchased must be a factor in any value equation.
  4. The non-jackpot prizes, since they cannot be shared and do not increase from drawing to drawing, will reduce to a simple constant in terms of the theoretical value of a ticket. (not actually true in California for some reason, so CA residents shouldn’t rely on this calculator too much)

To calculate the constant value of the non-jackpot prizes, I can use the odds and prizes printed right on the website of the lottery commission and add the resultant values of each together. For instance, a 1 in 50 chance of winning two dollars confers a pre-drawing value of 4 cents onto a random ticket.

The math is complicated, so I won’t post it all here, but if you’re interested you can read about it over at my personal blog.

Since the calculator involves knowing the number of tickets in play, I’ve worked out a formula for guesstimating the number of tickets sold for a Mega Millions or a Powerball drawing based on the going jackpot. To see it in action, fill in the cash prize amount and then click the appropriate setup link (or leave it blank and the current numbers will fill in for you automatically). I derived the formula using Excel’s trendline function. I’m actually pretty happy with my result. The R-squared value on what turned out to be a classic-looking quadratic was .9955 for Mega Millions and .9875 for Powerball, which is more than suitable for our purposes.

To quickly populate the settings for one of the two big US multi-state drawings, click one of the options below:
Set form for Mega Millions
Set form for Powerball

Jackpot Cash (not annuity) Value: $ million
State and Local Taxes:
(federal taxes automatically fixed at 25%)
%
Number of Tickets in Play: million
Jackpot Odds of Winning: 1: million
Other Prizes, Odds

Hypothetical value of 1 random lottery ticket:

April 02 2008 | ajax | 3 Comments »

Harrisonburg Blogs

Harrisonburg Blogs represents my first attempt at running a WordPress MU site. The intention is to create a portal where anyone living in or around my home city of Harrisonburg can enter into the blogging scene and easily connect with other bloggers who are already active. To that end, it will serve both as a blogging platform as well as a blog feed aggregator. The idea isn’t really original, and I freely admit that it’s mostly inspired (“stolen” being such an ugly word) by my experience with a website called chattablogs, which a friend of mine from college put together.

The fun thing about this is that I can get lots of ideas for new development tasks in order to take WordPress way beyond it’s typical capabilities. So far I’ve added in local news feeds, links to the most recent posts and comments sitewide, an ajax-based online poll, and I’ve developed a few new plugins to work both on the home page as well as the various hosted blogs. I’ve also been researching plugins written by others that I can tie in as well. So far my favorite is one called “Weather Icon,” which I use to show the current weather conditions in Harrisonburg.

What I most need now, in order to continue developing it further, are a few alpha testers who can help me find any bugs, suggest and test themes and plugins, and help turn my lone-wolf project into a true community effort. Chattablogs has become a treasure to the now-vibrant blogging scene in Chattanooga, and I’d just love to see the same thing happen here in my new hometown.

By the way, if you live in Harrisonburg, have some familiarity with WordPress, and would like to be an alpha tester, visit this page.

April 01 2008 | Schmategories | Comments Off on Harrisonburg Blogs

« Prev - Next »