I’ve just started developing a WP plugin, and i’ve been reading some code from other plugins as a way to get started. I’ve seen a couple of plugins that wrap all or some of their functions in the following code:
if(!function_exists('my_function')) {
function my_function() {
// a cool function
}
}
Is it considered good practice to wrap all functions in this code to avoid naming conflicts with other plugins?
Thanks
I would not do this to prevent naming conflicts: if another unrelated plugin uses the same name, it’s unlikely that they will provide the same functionality and your plugin can continue as normal. There you want to fail early, not sneaky later on. Or prevent the conflict with a better prefix of course 🙂
The only reason to do this is to create a pluggable function, a separate piece of functionality that can be implemented in a different way by an additional plugin. You can see this in the WordPress core code: functions like wp_mail() are pluggable so you can use a completely custom mailing system.
You also see this in themes that are likely to get child themes. The default themes, Twemty Eleven and Twenty Ten before it, are good examples of this. Child themes can define functions with the same name, and they will be used instead.
Personally, I don’t really like this approach to provide hooks for other code. They make it harder to figure out what code will be called (an my IDE code completion gets confused). I try to provide all extension points via “classic” actions and filters.