Main Content

Shipping a test harness with your class in PHP

Archive - Originally posted on "The Horse's Mouth" - 2010-02-12 18:08:48 - Graham Ellis

If you're writing a class (or group of classes) into a file you include into your main application(s) in PHP, you'll be recommended to keep the included files out of the document path so that they can't be run on their own (or, more dangerous, browsed as text if you have a different extension applied to them). But there is an alternative ...

If you code
  if ($_SERVER[SCRIPT_FILENAME] == __FILE__) {
after your class code, and include some sample calls to your classes and their methods, youcan provide a very useful test harness and demonstration - writing code that shows your user how you intended your class to be used, and also letting him/her check that the installation is complete and is running correctly.

During today's Object Oriented Programming in PHP training course, I wrote a complete example that showed a test harness (and also polymorphism, inheritance, statics, etc!) ... source code [here]. There's also a very small application page [here] which makes use of the classes in that file but ignores the test harness completely!