PHP Classes as namespaces?
May 9th, 2007I’ve only recently, in the last 6 months or so, began to take an object oriented approach to php development. In that time, I’ve all but fallen in love with it. Sure, php4 is limited in its OOP model, but the simplicity of it makes it strong. In the real world, multi-level inheritance isn’t that important, at least not to me. I would like to have the __get and __set functions available to me, but we can’t have everything, can we?
The problem is, though the core of most of my sites are OOP oriented, most of the functionality is procedural still. All of the supporting functions, for example, are just functions, and really have no place, or rather, would gain very little by making objects from them.
But I was thinking the other day, as I was going through the entire codebase of a site to find/replace a function name, about how nice it was to have namespaces in other languages. The problem in this instance was our redirect() function. We tied the whole site and punBB together, but punBB has a function called redirect() as well, and though similar in function, it did a little more than just redirection, so we didn’t want to just use it.
As I’m sure is true in most development shops, we have amassed a decent library of functions (custom) over the years. We know the names and usage of those functions as well as the core php functions. The problem is, some of them have pretty generic names, names that I’m sure are going to cause more function collisions down the line. This is where the objects come in. Our functions now are in a single file (well, multiple files, depending on the purpose of the contained functions: funcs, funcs_print, funcs_image, etc…) Making a class out of an entire file full of semi-related functions really serves no purpose other than to act as a namespace. For instance, the redirect function, is in funcs.php. If I had made a giant class out of funcs.php, then I would have been using something like
$funcs = new funcs_class();
$funcs->redirect('index.php');
I never would have had the problem with the function name. Now, granted, changing the current name and replacing in all the files was quick and easy, and honestly not too much trouble. That’s where the question comes in to play: Is making the change in code and habit worth the reward?
I guess, at some point, I will just have to try it. When I have a project in my lap with breathing room. For now, I will carry on as usual, since it works.
Leave a Reply