New Script: PHP Length Conversion Class
I was looking for a project to tackle today, and I decided to make a script that would convert lengths from one unit or system to another.
It doesn’t sound all that complicated - and it’s not. I had a working script in a few minutes, but I didn’t like it. It had too many functions to do conversions for individual units. I wanted this script to be pretty well abstracted so that I could easily add new unit types - and so that the source code for the class would be very short.
You can see what I came up with at the PHP Length Conversion Class page.
The Concept Behind the Class
Here’s the concept I came up with to help standardize the class, make the code manage-able, and make it adaptable.
First, when the length class is constructed the unit of length is converted to meters. By having a standard format, it cuts down a lot on the number of conversions I need to worry about. Although it means that each value will be converted twice (from the original into meters and then from meters into the next), it cuts down a lot on overhead.
Originally, I had written functions to convert from one type to meters and vice versa. This was fine when I just had five data types, but I could see it would quickly get out of hand - and it would be tough to add new unit types.
I decided that I needed a data file (or a hard-coded data array in the class). I came up with a format for an xml file that holds all the pertinent information - the abbreviation and the ratio of the unit type to meters.
Now, the class can read the XML file, create an array of available data types, and quickly convert between one unit type and another. This enabled me to standardize the class methods - so now it only contains a handful of methods.
It could use some robustness in the way of data checking and error reporting - but for the moment I’m assuming the implementer checks that the data being passed to the class is the proper type.







Leave a Reply