Topics
- PHP
- Single and Double Quotes
- Indentation
- Brace Style
- Regular Expressions
- No Shorthand PHP Tags
- Remove Trailing Spaces
- Space Usage
- Formatting SQL statements
- Database Queries
- Naming Conventions
- Self-Explanatory Flag Values for Function Arguments
- Ternary Operator
- Yoda Conditions
- Clever Code
- Error Control Operator
@
- Credits
Some parts of the WordPress code structure for PHP markup are inconsistent in their style. WordPress is working to gradually improve this by helping users maintain a consistent style so the code can become clean and easy to read at a glance.
Keep the following points in mind when writing PHP code for WordPress, whether for core programming code, plugins, or themes. The guidelines are similar to Pear standards in many ways, but differ in some key respects.
See also: PHP Documentation Standards.
PHP #
Single and Double Quotes #
Use single and double quotes when appropriate. If you’re not evaluating anything in the string, use single quotes. You should almost never have to escape quotes in a string, because you can just alternate your quoting style, like so:
echo '<a href="/static/link" title="Yeah yeah!">Link name</a>'; echo "<a href='$link' title='$linktitle'>$linkname</a>";
Text that goes into attributes should be run through esc_attr()
so that single or double quotes do not end the attribute value and invalidate the HTML and cause a security issue. See Data Validation in the Codex for further details.
Indentation #
Your indentation should always reflect logical structure. Use real tabs and not spaces, as this allows the most flexibility across clients.
Exception: if you have a block of code that would be more readable if things are aligned, use spaces:
[tab]$foo = 'somevalue'; [tab]$foo2 = 'somevalue2'; [tab]$foo34 = 'somevalue3'; [tab]$foo5 = 'somevalue4';
For associative arrays, values should start on a new line. Note the comma after the last array item: this is recommended because it makes it easier to change the order of the array, and makes for cleaner diffs when new items are added.
$my_array = array( [tab]'foo' => 'somevalue', [tab]'foo2' => 'somevalue2', [tab]'foo3' => 'somevalue3', [tab]'foo34' => 'somevalue3', );
Rule of thumb: Tabs should be used at the beginning of the line for indentation, while spaces can be used mid-line for alignment.
Brace Style #
Braces shall be used for all blocks in the style shown here:
if ( condition ) { action1(); action2(); } elseif ( condition2 && condition3 ) { action3(); action4(); } else { defaultaction(); }
Furthermore, if you have a really long block, consider whether it can be broken into two or more shorter blocks or functions. If you consider such a long block unavoidable, please put a short comment at the end so people can tell at glance what that ending brace ends – typically this is appropriate for a logic block, longer than about 35 rows, but any code that’s not intuitively obvious can be commented.
Braces should always be used, even when they are not required:
if ( condition ) { action0(); } if ( condition ) { action1(); } elseif ( condition2 ) { action2a(); action2b(); } foreach ( $items as $item ) { process_item( $item ); }
Note that requiring the use of braces just means that single-statement inline control structures are prohibited. You are free to use the alternative syntax for control structures (e.g. if
/endif
, while
/endwhile
)—especially in your templates where PHP code is embedded within HTML, for instance:
<?php if ( have_posts() ) : ?> <div class="hfeed"> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID() ?>" class="<?php post_class() ?>"> <!-- ... --> </article> <?php endwhile; ?> </div> <?php endif; ?>
Regular Expressions #
Perl compatible regular expressions (PCRE, preg_
functions) should be used in preference to their POSIX counterparts. Never use the /e
switch, use preg_replace_callback
instead.
It’s most convenient to use single-quoted strings for regular expressions since, contrary to double-quoted strings, they have only two metasequences: \'
and \\
.
No Shorthand PHP Tags #
Important: Never use shorthand PHP start tags. Always use full PHP tags.
Correct:
<?php ... ?> <?php echo $var; ?>
Incorrect:
<? ... ?> <?= $var ?>
Remove Trailing Spaces #
Remove trailing whitespace at the end of each line of code. Omitting the closing PHP tag at the end of a file is preferred. If you use the tag, make sure you remove trailing whitespace.
Space Usage #
Always put spaces after commas, and on both sides of logical, comparison, string and assignment operators.
x == 23 foo && bar ! foo array( 1, 2, 3 ) $baz . '-5' $term .= 'X'
Put spaces on both sides of the opening and closing parenthesis of if
, elseif
, foreach
, for
, and switch
blocks.
foreach ( $foo as $bar ) { ...
When defining a function, do it like so:
function my_function( $param1 = 'foo', $param2 = 'bar' ) { ...
When calling a function, do it like so:
my_function( $param1, func_param( $param2 ) );
When performing logical comparisons, do it like so:
if ( ! $foo ) { ...
When type casting, do it like so:
foreach ( (array) $foo as $bar ) { ... $foo = (boolean) $bar;
When referring to array items, only include a space around the index if it is a variable, for example:
$x = $foo['bar']; // correct $x = $foo[ 'bar' ]; // incorrect $x = $foo[0]; // correct $x = $foo[ 0 ]; // incorrect $x = $foo[ $bar ]; // correct $x = $foo[$bar]; // incorrect
Formatting SQL statements #
When formatting SQL statements you may break it into several lines and indent if it is sufficiently complex to warrant it. Most statements work well as one line though. Always capitalize the SQL parts of the statement like UPDATE
or WHERE
.
Functions that update the database should expect their parameters to lack SQL slash escaping when passed. Escaping should be done as close to the time of the query as possible, preferably by using $wpdb->prepare()
$wpdb->prepare()
is a method that handles escaping, quoting, and int-casting for SQL queries. It uses a subset of the sprintf()
style of formatting. Example :
$var = "dangerous'"; // raw data that may or may not need to be escaped $id = some_foo_number(); // data we expect to be an integer, but we're not certain $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) );
%s
is used for string placeholders and %d
is used for integer placeholders. Note that they are not ‘quoted’! $wpdb->prepare()
will take care of escaping and quoting for us. The benefit of this is that we don’t have to remember to manually use esc_sql()
, and also that it is easy to see at a glance whether something has been escaped or not, because it happens right when the query happens.
See Data Validation in the Codex for more information.
Database Queries #
Avoid touching the database directly. If there is a defined function that can get the data you need, use it. Database abstraction (using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster.
If you must touch the database, get in touch with some developers by posting a message to the wp-hackers mailing list. They may want to consider creating a function for the next WordPress version to cover the functionality you wanted.
Naming Conventions #
Use lowercase letters in variable, action, and function names (never camelCase
). Separate words via underscores. Don’t abbreviate variable names un-necessarily; let the code be unambiguous and self-documenting.
function some_name( $some_variable ) { [...] }
Class names should use capitalized words separated by underscores. Any acronyms should be all upper case.
class Walker_Category extends Walker { [...] } class WP_HTTP { [...] }
Constants should be in all upper-case with underscores separating words:
define( 'DOING_AJAX', true );
Files should be named descriptively using lowercase letters. Hyphens should separate words.
my-plugin-name.php
Class file names should be based on the class name with class-
prepended and the underscores in the class name replaced with hyphens, for example WP_Error
becomes:
class-wp-error.php
This file-naming standard is for all current and new files with classes. There is one exception for three files that contain code that got ported into BackPress: class.wp-dependencies.php, class.wp-scripts.php, class.wp-styles.php. Those files are prepended with class.
, a dot after the word class instead of a hyphen.
Files containing template tags in wp-includes
should have -template
appended to the end of the name so that they are obvious.
general-template.php
Self-Explanatory Flag Values for Function Arguments #
Prefer string values to just true
and false
when calling functions.
// Incorrect function eat( $what, $slowly = true ) { ... } eat( 'mushrooms' ); eat( 'mushrooms', true ); // what does true mean? eat( 'dogfood', false ); // what does false mean? The opposite of true?
Since PHP doesn’t support named arguments, the values of the flags are meaningless, and each time we come across a function call like the examples above, we have to search for the function definition. The code can be made more readable by using descriptive string values, instead of booleans.
// Correct function eat( $what, $speed = 'slowly' ) { ... } eat( 'mushrooms' ); eat( 'mushrooms', 'slowly' ); eat( 'dogfood', 'quickly' );
Ternary Operator #
Ternary operators are fine, but always have them test if the statement is true, not false. Otherwise, it just gets confusing. (An exception would be using ! empty()
, as testing for false here is generally more intuitive.)
For example:
// (if statement is true) ? (do this) : (else, do this); $musictype = ( 'jazz' == $music ) ? 'cool' : 'blah'; // (if field is not empty ) ? (do this) : (else, do this);
Yoda Conditions #
if ( true == $the_force ) { $victorious = you_will( $be ); }
When doing logical comparisons, always put the variable on the right side, constants or literals on the left.
In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true
. If the statement were the other way around ( $the_force = true )
, the assignment would be perfectly valid, returning 1
, causing the if statement to evaluate to true
, and you could be chasing that bug for a while.
A little bizarre, it is, to read. Get used to it, you will.
This applies to ==, !=, ===, and !==. Yoda conditions for <, >, <= or >= are significantly more difficult to read and are best avoided.
Clever Code #
In general, readability is more important than cleverness or brevity.
isset( $var ) || $var = some_function();
Although the above line is clever, it takes a while to grok if you’re not familiar with it. So, just write it like this:
if ( ! isset( $var ) ) { $var = some_function(); }
Error Control Operator @
#
As noted in the PHP docs:
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
While this operator does exist in Core, it is often used lazily instead of doing proper error checking. Its use is highly discouraged, as even the PHP docs also state:
Warning: Currently the “@” error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use “@” to suppress errors from a certain function and either it isn’t available or has been mistyped, the script will die right there with no indication as to why.
Credits #
- PHP standards: Pear standards
Major Changes #
- June 20, 2014: Add section to discourage use of the error control operator (
@
). See #wordpress-dev. - November 13, 2013: Braces should always be used, even when they are optional
- October 20, 2014: Update brace usage to indicate that the alternate syntax for control structures is allowed, even encouraged. It is single-line inline control structures that are forbidden.
Tom Willmot 11:42 am on April 12, 2013 Permalink | Log in to Reply
The code example for the “Yoda Conditions” block is missing a space between the `if` and the opening parenthesis `(`, it should be `if ( true == $the_force ) {` instead of `if( true == $the_force ) {`
Tom Willmot 1:27 pm on April 12, 2013 Permalink | Log in to Reply
Happy to edit it myself if thats possible
Kim Parsell 2:12 pm on April 12, 2013 Permalink | Log in to Reply
Fixed – thanks for pointing that out.
zilli 6:39 am on April 17, 2013 Permalink | Log in to Reply
Twenty Thirteen and _s themes are using if-endif brace style. A lot of developers prefer this style too over the traditional {}.
Isn’t time to update the handbook?
daigo75 5:12 pm on May 2, 2013 Permalink | Log in to Reply
I think that braces are just fine, I don’t like the “if-endif” style at all (I’m not a fan of Yoda statements either).
Zilli 8:50 am on September 11, 2013 Permalink | Log in to Reply
I don’t think it’s about taste, but standards. I think both syntaxes should be ok, otherwise if I’m a newbie and I use Twenty Thirteen or _s as my objects of learning… I’ll be doing ‘wrong’ without knowing.
J.D. Grimes 8:29 pm on May 29, 2013 Permalink | Log in to Reply
if-endif is more readable when used in HTML, for example a page template. But I prefer braces everywhere else.
Antonio 8:33 am on June 8, 2013 Permalink | Log in to Reply
Please Do Not Use Curly Brackets {} in Template Files
TuKod dot Com 8:56 am on May 9, 2014 Permalink | Log in to Reply
I think the real question has not been addresses.
Are we placing php into html?
Or putting html into php?
In other words, are they template pages, or code processing pages?
A day is coming where people will see the power and value of separating the “code process” from the “template output.”
Consider a template in which no php exist other than if/endif control, <?= $var >, for var output, and perhaps a call to a function in a class. Everything else in the template would be html!
If the code you are working on is mostly php, then most would agree that braces are the cleanest way to go. With editors that do “Indentation Guides” (Geany, Notepad++, etc.) this makes code reading easy.
On the other hand, if your code is mainly html, and you are only inserting php for control or to pop in a variables, then the if/endif structure and <?= $var >, is more readable for insertion into an html template.
This is actually the same with short tags. <? was a nightmare. However, <?= $var > should be encouraged in templates. Even in the php core itself, the short tag < is being deprecated, whereas the short echo <?= will soon be a default, and will not even need to be enabled!
The php gods themselves have smiled on <?= $var > and it only remains to see how much time it takes before the WordPress Core makes this an acceptable template standard as well.
Weston Ruter 5:16 pm on October 20, 2014 Permalink | Log in to Reply
I don’t believe the handbook here is trying to say that the alternative syntax for control structures is prohibited, just that single-line inline control structures are. This is how the WordPress Coding Standards for PHP_CodeSniffer have interpreted this.
There currently 105 instances of the alternative syntax being used in Core, including the newly-added Twenty Fifteen theme.
Weston Ruter 5:28 pm on October 20, 2014 Permalink | Log in to Reply
I’ve updated the handbook to indicate that the alternative syntax is allowed, even encouraged: https://make.wordpress.org/core/handbook/coding-standards/php/#brace-style
Weston Ruter 5:35 pm on October 20, 2014 Permalink | Log in to Reply
See also https://core.trac.wordpress.org/ticket/24549 which has been closed wontfix. Alternative syntax for control structures are here to stay.
Kailey Lampert (trepmal) 6:14 am on May 7, 2013 Permalink | Log in to Reply
Under No Shorthand PHP tags
<?php = $var ?>
should be<?php echo $var ?>
Kim Parsell 11:22 am on May 8, 2013 Permalink | Log in to Reply
Fixed. Thanks Kailey!
MK Safi 3:05 pm on May 24, 2013 Permalink | Log in to Reply
You need to explain your “Space Usage”. It seems arbitrary to me and I have a hard time remembering the specifics because I don’t know why I’m doing it…
Aaron D. Campbell 3:56 pm on May 29, 2013 Permalink | Log in to Reply
All the spacing is for readability. In our experience, this spacing produces the easiest to read code, and prevents accidental missteps. For example, spacing the ! away from the variable or function in an if statement makes it stand out so it’s easy to see at a glance what’s going on.
Looimaster 12:54 pm on June 15, 2013 Permalink | Log in to Reply
It’s also a little weird for me that spaces should go everywhere. I see such standard for the first time in WordPress. I have a 1200 pages book about PHP (one of the best in the world at this moment) and they do it like this: http://pear.php.net/manual/en/standards.funcdef.php and like php.net – http://pl1.php.net/manual/en/function.function-exists.php (they never put additional spaces after every single quote and every bracket). Is this something that is likely to change in the future? This is not a PHP standard.
George Stephanis 5:13 pm on June 22, 2013 Permalink | Log in to Reply
There is no ‘PHP Standard’. There are a number of competing standards (CodeIgniter, Zend, Symfony, the PEAR one you linked, others…), we’ve just chosen one that works for us, and try to be consistent with it.
The WP Coding Standards for PHP are not likely to change in the near future, no.
Just always indent with tabs, and we won’t have a problem.
lwoods 8:34 pm on June 23, 2013 Permalink | Log in to Reply
I recommend discouraging the use of the PHP increment and decrement operators except where necessary, such as in the ‘for’ comment:
If you are not familiar with this operator:
$i = 5;
echo ++$i; // display 6
echo $i–; // display 6 again
echo $i; // display 5
In debugging code it is very easy to miss the effect of these operators.
On the other hand, it is common and encouraged to use these operators in the ‘for’ loop:
for ( $j=0; $j<5; $j++ ){
.
.
.
}
lwoods 8:38 pm on June 23, 2013 Permalink | Log in to Reply
I disagree with the following under “Brace Style”:
Single line blocks can omit braces for brevity:
if ( condition )
action1();
elseif ( condition2 )
action2();
else
action3();
ALL IF statements should be braced! Although they are not needed in the above example the absence of braces can be very confusing if you start nesting IF statements. I have seen multiple single line blocks in nested IF statements that were near to impossible to debug.
Dayjo 2:00 pm on July 10, 2013 Permalink | Log in to Reply
I agree with @lwoods.
I find that the “Clever Code” part of this document contradicts “Yoda Conditions”.
I find reading Yoda Conditions much slower than normal conditions. It seems that Yoda Conditions are just there to prevent you from writing broken code, which you should just not do. Learn to use the correct numbe of = instead.
This also applies to the example in the Ternary Operator section which uses a Yoda Condition.
To me, ( ‘jazz’ == $music ) … would return true.. because jazz is music. Whereas ( $music == ‘jazz’ ), or even ( $music_genre == ‘jazz’ ) makes so much more sense.
Andrew Nacin 2:49 pm on July 11, 2013 Permalink | Log in to Reply
Yoda conditions are a programming best practice, and not overly clever. They’re going to remain part of the standard. Thanks for your input.
markparolisi 12:14 pm on July 21, 2013 Permalink | Log in to Reply
I wouldn’t call them a programming best practice since many languages wouldn’t even let you declare variables inside a condition. The best way to avoid this problem is to avoid declaring variables in that way. It serves no purpose but to save yourself one line of code.
Gary Jones 10:57 am on July 24, 2013 Permalink | Log in to Reply
It’s not declaring anything. It’s trying to avoid accidental assignment to a variable.
TuKod dot Com 9:28 am on May 9, 2014 Permalink | Log in to Reply
Honestly Andrew, I teach my students to use Yoda Conditions, for their benefit, to try to trap their errors before they have to labor over them. However, honestly most would rather use “Logical Conditions” (the opposite of Yoda Conditions!)
One of my students recommended simply debugging with a “mark” search for ‘ = ‘. A visual scan of the page will usually expose any incorrect Logical Condition. Almost as simply as Yoda Conditions.
Likewise, virtually everyone would admit a properly formated Logical Condition is easier to read that an equivalent properly formated Yoda Condition. So calling Yoda Conditions a best practice is a bit of a stretch when refining code blocks (as in future updates).
My suggestion would be simply to suggest Yoda Conditions, rather than elevate them to the level of “Best Practice” or the higher level of a “Standard!”
That is my opinion, but like armpits, we all have a couple of them!
However… I have been reading a lot of WordPress code (plugins, themes, etc.) that violate the Yoda Conditions “Standard”, it would be interesting to test this with a simple search for something like
== ‘
or
== ”
This would be a good test for the Yoda police to use in accepting new themes and plugins!
The force with you, maybe?
Star Wars 7 is coming with the original cast of the first movie! Will Yoda be there in spirit?
Jon Brown 6:41 am on July 11, 2013 Permalink | Log in to Reply
Regarding braces and php tags, I run into this where php tags get thier own line often:
personally, I prefer this:
I’m really not sure which is right/wrong in the WordPress universe. Reviewing core, I think I’m right? Which is the WP way?
Andrew Nacin 2:52 pm on July 11, 2013 Permalink | Log in to Reply
I don’t think WordPress is particularly consistent either way. At the moment, it depends on what is most readable for that situation. (Also, in general, we use if/endif when we are forced to break into HTML.)
TuKod dot Com 7:58 am on May 9, 2014 Permalink | Log in to Reply
Hey Jon and Andrew!
Our shop puts the closing php at the end of the php block, and the opening php at the end of the HTML.
This makes good reading on editors like Geany and NotepadPlusPlus that have “Indentation Guides.” Like this…
function do_stuff() {
if ( condition ) { ?>
. It also gives a good visual clue that the php has stopped and the HTML has started when reading the php source.
Like this…
function do_stuff() {
if ( condition ) { ?>
<?php
}
}
Of course, as you pointed out, this comes from my familiarity with the "change at the end of the line programming" dating back to work at ARPA (later called DARPA) in the early 1970's But I noticed it applied well to the newly introduced PHP in the mid to late 1990's.
TuKod dot Com 8:14 am on May 9, 2014 Permalink | Log in to Reply
OOPS! The above should be,,,
Hey Jon and Andrew!
Our shop puts the closing php at the end of the php block, and the opening php at the end of the HTML.
This makes good reading on editors like Geany and NotepadPlusPlus that have “Indentation Guides.” Like this…
<?php } }
And… By adding a blank line before the html, it contracts the loss of a line at the close of php. This makes the output html more readable. It also gives a good visual clue that the php has stopped and the HTML has started when reading the php source.
Like this…
<?php } }
Of course, as you pointed out, this comes from my familiarity with the “change at the end of the line programming” dating back to work at ARPA (later called DARPA) in the early 1970’s But I noticed it applied well to the newly introduced PHP in the mid to late 1990’s.
TuKod dot Com 11:26 am on May 12, 2014 Permalink | Log in to Reply
Personally, I prefer this:
function
do_stuff() {
if
( condition ) { ?>
<ul>
<li>something1</li>
<li>something2</li>
<ul><?php
}
}
The blank line afrer the <ul> makes the HTML source look good.
Jon Brown 6:00 am on July 16, 2013 Permalink | Log in to Reply
Thanks Nacin. Personally I hate if/endif. I find my later example much more readable, but that’s probably more familiarity with that style than an objective opinion.
lesterbuck 4:57 pm on July 17, 2013 Permalink | Log in to Reply
I am new to PHP and WordPress, so I looked for tools that do the formatting and checking for me. I have exactly zero interest or opinion in what the format should be. I just want to match the standard, and I want a tool to check/fix that automatically as I check in to my source repository. (Computers are good at that, and I have better places to apply my mental energy.)
I am not using a commercial IDE, such as Coda, which has reformatting built in. After some searching, I found wp-phptidy for reformatting, and PHP Codesniffer with the WordPress standard addon. Great, huh? Well, not exactly. wp-phptidy wants to indent the switch and case statements so they are at the same indent, while PHP Codesniffer with the WordPress standard complains if the case statements are not indented further than the switch statement.
Note: I couldn’t care less which it is, I just want an automated tool to reformat it automatically if I indent something incorrectly, and check for valid format as I am committing the file to my repository.
Ok, one of these tools is “wrong”, right? I consult the WordPress PHP coding standard and find … nothing about indenting switch statements. Well, I’ll just look at WordPress core and see what they use, right? Well, that doesn’t work either. Just look at wp-includes/functions.php and note that in one file there are multiple uses of both indent styles.
Lots of tools exist to indent code to a given standard, automatically, and there is a document entitled “WordPress Coding Standards”, but the existing code base can’t be bothered to actually follow a consistent style, any style?
J.D. Grimes 9:24 pm on August 17, 2013 Permalink | Log in to Reply
My preference is to indent
case
within theswitch
, and then to put abreak
at the end of the case on the same level as the case:Are there anything like this within the standards?
J.D. Grimes 9:17 pm on August 17, 2013 Permalink | Log in to Reply
I noticed this type of spacing today (in wp-db.php):
case 'string' : // note space before colon
Is this part of the spacing standards, or just a random act of code?
hjchin 5:03 pm on August 25, 2013 Permalink | Log in to Reply
I might be being silly. In the Yoda Conditions, why would I want to compare a variable to a boolean at the first? Isn’t it simpler and straightforward to write it as following? Please correct me if i’m wrong.
if ( $the_force ) {
$victorious = you_will( $be );
}
J.D. Grimes 4:17 pm on August 26, 2013 Permalink | Log in to Reply
You’re right, in that example, it doesn’t really make sense. It should be a strict check with
===
.Frankie Jarrett 2:58 pm on March 10, 2014 Permalink | Log in to Reply
Should extra space padding also be applied when an array index contains a concatenated string?
$x = $foo[ 'bar_' . $baz ];
$x = $foo[ $bar . '_baz' ];
Frankie Jarrett 7:35 pm on March 10, 2014 Permalink | Log in to Reply
Or an alternative syntax would be:
$x = $foo[ "bar_$baz" ];
Mike Manger 2:33 pm on April 3, 2014 Permalink | Log in to Reply
I am pondering the same thing but I think “only include a space around the index if it is a variable” applies to this (you are concatenating the string to a variable).
I think adding a concatenation example to the list would help clear up some confusion.
J.D. Grimes 9:13 pm on July 18, 2014 Permalink | Log in to Reply
Yes, I generally do this:
$x = $foo[ "bar_{$baz}" ];
Andrés Villarreal 8:53 pm on March 20, 2014 Permalink | Log in to Reply
Should Pear Standards be applied for all cases that are not covered by the Handbook, or any other standard will be taken as valid? I couldn’t find any specification about this point.
Eric Andrew Lewis 2:51 am on April 4, 2014 Permalink | Log in to Reply
Regarding the “Clever Code” example of what not to do:
isset( $var ) || $var = some_function();
, we do a crapload of this in JS. Why would this not be cool for PHP?Scott Kingsley Clark 5:25 pm on May 4, 2014 Permalink | Log in to Reply
I’d like to recommend all comparison operators in statements such as
< <= > >=
always be placed lowest to highest. removing usage of> >=
:if ( 0 < $var ) {
if ( $var < 1 ) {
if ( $var <= $other_var ) {
It effectively gets rid of any >= or > usage, and in this way, there is never any confusion as to the logic when reading over the code.
TuKod dot Com 9:32 am on May 9, 2014 Permalink | Log in to Reply
Hey Scott, over 4 decades ago we only used < and > and everything worked just fine!
michalzuber 4:12 pm on July 16, 2014 Permalink | Log in to Reply
http://www.phptherightway.com/ has some good resources too.
Daniel Bachhuber 11:33 am on July 17, 2014 Permalink | Log in to Reply
The indentation section says:
I believe this statement makes assumptions, and would be best backed up with examples. I’d propose:
Daniel Bachhuber 11:35 am on July 17, 2014 Permalink | Log in to Reply
Gah. I guess you can’t do `
Daniel Bachhuber 11:39 am on July 17, 2014 Permalink | Log in to Reply
This is what I was going for: https://gist.github.com/danielbachhuber/8934c3c4103389550b43
J.D. Grimes 9:20 pm on July 18, 2014 Permalink | Log in to Reply
I like to use the complex syntax for variables in strings:
$x = "I like {$foo}";
I think it helps to draw the eye to the interpolated variables. Of course, many times this would be in strings that need to be translated anyway, so you’d need to use
sprintf()
, which is even better.silb3r 6:20 pm on July 28, 2014 Permalink | Log in to Reply
Is there any chance of getting the “always use tabs” rule changed to “always use spaces”? I know this is a huge debate throughout the development community but clearly the current WP standard is on the wrong side of the fence.
Tabs severely affect readability (negatively) and could make for compatibility issues across OSs.
Knut Sparhell 4:29 am on July 29, 2014 Permalink | Log in to Reply
Tabs are used for indentation at the beginning of a line. Elsewhere spaces should be used. Indentation is used for readability.
Could you elaborate what is wrong with this? References to this debate?
J.D. Grimes 8:04 pm on July 31, 2014 Permalink | Log in to Reply
I’ve dealt with space-indented code before, and it seems to have a higher tendency to be unreadable than tab-indented code does. It’s just naturally messier.
Mike Schinkel 9:39 pm on August 28, 2014 Permalink | Log in to Reply
Funny, my experience is tab-oriented code is messier.
Lance Willett 3:51 pm on August 5, 2014 Permalink | Log in to Reply
WordPress Code Sniffer library on GitHub: https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards
Misamee 6:47 am on October 6, 2014 Permalink | Log in to Reply
I can’t completely I agree with this: https://make.wordpress.org/core/handbook/coding-standards/php/#self-explanatory-flag-values-for-function-arguments
Letting the user writing strings is prone to human mistake.
True and False can’t be mistakenly written, but I agree that it’s hard to guess the meaning of them.
I would rather use constants, probably writing something like that:
/* Constants */
define('EAT_SLOWLY', 0);
define('EAT_MODERATELY', 0.25);
...
define('EAT_FAIRLY_QUICKLY', 0.75);
define('EAT_QUICKLY', 1);
function eat( $what, $speed = EAT_SLOWLY ) {
...
}
eat( 'mushrooms' );
eat( 'mushrooms', EAT_SLOWLY );
eat( 'dogfood', EAT_QUICKLY);
Some PHPDOC before the function would help explaining what values are allowed – after all, even with the “string way” the PHPDOC would be needed, which would also sort of fix the case where boolean is used: I don’t know about others, but when I use a function I don’t (fully) know, I always go to its definition anyway, check the PHPDOC or its code if the PHPDOC is not enough.
kesarr 8:52 am on October 16, 2014 Permalink | Log in to Reply
Same feeling. What about this:
TuKod dot Com 12:13 am on October 30, 2014 Permalink | Log in to Reply
Class File Naming Conventions
Considering “spl_autoload_register” – wouldn’t apending “-class” make more sence than prepending “class-” ?
Example WP_Error becomes “wp-error-class.php”
Or perhaps just following the spl_autoload_register example “wp-error.class.php” – ending the file name with “.class.php”
TuKod dot Com 12:52 am on October 30, 2014 Permalink | Log in to Reply
For example, this works great for me… in
./zozo.php
Note that all files end with “.class.php” and are in/under the folder containing the autoloader above. In this case that folder is named “./zoe/”
./zozo.php
./zoe/main.class.php
./zoe/general.class.php
./zoe/controllers/something_one.php
./zoe/models/something_two.php