Using a namespace for your functions and classes

April 15th, 2011 – 5 Comments

An often made mistake by WordPress developers is to use to generic function and class names. For instance, if you’re building a plugin to do with YouTube, using a class name “Youtube” is bound to cause issues: if a user has multiple plugins dealing with Youtube, he or she could very well end up with two plugins that have a class Youtube, which would immediately cause a crash. The only way of fixing that would be to remove either of the two plugins.

The best thing to do in these cases is to use one or more classes for your plugin, and to use a namespace for these. So, for instance, a class called “YoastYoutube” instead of “Youtube”. One of the benefits of using a class is that the function names within that class can be short and concise and need not be namespace. So you could have a function get(), within that class, and it would never break anything.

This is also valid for other instances where your chosen names might collide: custom taxonomies and custom post types, widget names and also specific hooks for actions and filters that you add to your plugin or theme.

5 Responses to Using a namespace for your functions and classes

  1. Marcus
    By Marcus on 22 April, 2011

    long gone are the old days of my_special_function_that_wont_conflict_with_other_plugin_function_name() functions, so much easier to read code this way!

    mind you, my opinion, the long functions do have their benefits on occasion if used sparingly

  2. Danny
    By Danny on 17 April, 2011

    Ironic sidenote here is that developers who are NOT using classes or namespaces for their plugins cannot even have two plugins of their own activated on the same install. :))

  3. lycog
    By lycog on 17 April, 2011

    Very informative. I’ll stay away from it.

  4. Dave Doolin
    By Dave Doolin on 16 April, 2011

    So simple, yet so few plugin developers seem to do this correctly. Although I’m seeing more namespacing in the plugins which are 2010 and newer, or under active development. Older plugins, not so much.

  5. Sander
    By Sander on 15 April, 2011

    Indeed, it happens too often! I’ve found this out the hard way myself ;-) Thanks for pointing this out!

    Greets, Sander

Check out our must read articles about Analytics