I was writing some code recently and wanted to know the best way to name my PHP class, as well as the name of the file that would house the class. It turns out that class names should be capitalized words separated by underscores, e.g. Foo_Bar_Thing. And the name of the file should have a prefix of “class-”, underscores replaced with hyphens and all lowercase letters. e.g. class-foo-bar-thing.php. I found this information inside the Naming Conventions section within the PHP Coding Standards, which is part of the official WordPress Contributor Handbook.
PHP Coding Standards
Just read through the standards for PHP code in WordPress and I am sure you will learn a thing or two. For me, it was the reason behind why Yoda Conditions are used. I had always wondered and it always seemed backwards to me, but now it finally makes sense. I will be changing my code to use this standard.
What About HTML, CSS and Javascript?
Yep, those are covered too:
- HTML Coding Standards
- CSS Coding Standards
- Javascript Coding Standards
Do They Only Apply to WordPress?
Absolutely not! These are standards that you could adopt on any project. No matter what server side language you use, or even if you have no server code at all.
WordPress PHP Documentation Standards
/** * Define the metabox and field configurations. * * @param array $meta_boxes * @return array */ function cmb_sample_metaboxes( array $meta_boxes ) { //do stuff }
Why Bother With Standards?
The reason the coding standards exist is to help avoid common issues, improve readability, but the most important thing to me is to make it really easy for other developers to collaborate together on the code. If everyone is doing things in the same way, then the learning curve is less and it is easier for others to find and fix bugs, or make enhancements.
Why You Must Bother
If you are planning to contribute to WordPress core, then you need to follow the standards in order for your code to be accepted. That seems like a very good reason. And even if you will never contribute to core, following other proven best practices seems like a good idea to me.