Skip to content

Commit f51392f

Browse files
dingo-djrfnl
authored andcommitted
Update wordpress-coding-standards/php.md
Textual update of the PHP coding standards document. Includes: * Removing outdated references to PEAR, BackPress and the defunct Hackers mailinglist. * Updating various texts to be in line with the current state of PHP. * Removed unnecessary "PHP" H2 subheader. * Changed the rest of the headers from H3 to H2. * Removed the credits and changelog as they were wildly inaccurate and out of date. * Various small textual clarifications and grammar improvements.
1 parent 69882e8 commit f51392f

File tree

1 file changed

+47
-58
lines changed
  • wordpress-coding-standards

1 file changed

+47
-58
lines changed

wordpress-coding-standards/php.md

Lines changed: 47 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
# PHP Coding Standards
22

3-
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.
3+
WordPress aims for a consistent code-style and for complying with established best practices for code readability, clean code, security and interoperability with plugins and themes for all PHP code in the WordPress Core codebase.
44

5-
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](https://pear.php.net/manual/en/standards.php) in many ways, but differ in some key respects.
5+
While not all code may fully comply with these standards (yet), all newly committed and/or updated code should fully comply with these coding standards.
66

7-
See also: [PHP Inline Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/php/).
7+
Keep the following rules in mind when writing PHP code for WordPress, whether for core programming code, plugins, or themes.
88

9-
## PHP
9+
Also see the [PHP Inline Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/php/) for further guidelines.
1010

11-
### Single and Double Quotes
11+
## Single and Double Quotes
1212

1313
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:
1414

@@ -17,11 +17,11 @@ echo '<a href="/static/link" title="Yeah yeah!">Link name</a>';
1717
echo "<a href='$link' title='$linktitle'>$linkname</a>";
1818
```
1919

20-
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](https://developer.wordpress.org/plugins/security/data-validation/) in the Plugin Handbook for further details.
20+
Text that goes into HTML attributes should be run through `esc_attr()` so that single or double quotes do not end the attribute value and invalidate the HTML, causing a security issue. See [Data Validation](https://developer.wordpress.org/plugins/security/data-validation/) in the Plugin Handbook for further details.
2121

22-
### Indentation
22+
## Indentation
2323

24-
Your indentation should always reflect logical structure. Use **real tabs** and **not spaces**, as this allows the most flexibility across clients.
24+
Your indentation should always reflect logical structure. Use **real tabs**, **not spaces**, as this allows the most flexibility across clients.
2525

2626
Exception: if you have a block of code that would be more readable if things are aligned, use spaces:
2727

@@ -59,7 +59,7 @@ $my_array = array(
5959
);
6060
```
6161

62-
For `switch` structures `case` should indent one tab from the `switch` statement and `break` one tab from the `case` statement.
62+
For `switch` control structures, `case` statements should be indented one tab from the `switch` statement and the contents of the `case` should be indented one tab from the `case` condition statement.
6363

6464
```php
6565
switch ( $type ) {
@@ -74,7 +74,7 @@ switch ( $type ) {
7474

7575
**Rule of thumb:** Tabs should be used at the beginning of the line for indentation, while spaces can be used mid-line for alignment.
7676

77-
### Brace Style
77+
## Brace Style
7878

7979
Braces shall be used for all blocks in the style shown here:
8080

@@ -111,7 +111,7 @@ foreach ( $items as $item ) {
111111
}
112112
```
113113

114-
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](https://www.php.net/manual/en/control-structures.alternative-syntax.php) (e.g. `if`/`endif`, `while`/`endwhile`)—especially in your templates where PHP code is embedded within HTML, for instance:
114+
Note that requiring the use of braces means that _single-statement inline control structures_ are prohibited. You are free to use the [alternative syntax for control structures](https://www.php.net/manual/en/control-structures.alternative-syntax.php) (e.g. `if`/`endif`, `while`/`endwhile`)—especially in templates where PHP code is embedded within HTML, for instance:
115115

116116
```php
117117
<?php if ( have_posts() ) : ?>
@@ -125,17 +125,17 @@ Note that requiring the use of braces just means that _single-statement inline c
125125
<?php endif; ?>
126126
```
127127

128-
### Use `elseif`, not `else if`
128+
## Use `elseif`, not `else if`
129129

130130
`else if` is not compatible with the colon syntax for `if|elseif` blocks. For this reason, use `elseif` for conditionals.
131131

132-
### Declaring Arrays
132+
## Declaring Arrays
133133

134134
Using long array syntax ( `array( 1, 2, 3 )` ) for declaring arrays is generally more readable than short array syntax ( `[ 1, 2, 3 ]` ), particularly for those with vision difficulties. Additionally, it's much more descriptive for beginners.
135135

136136
Arrays must be declared using long array syntax.
137137

138-
### Closures (Anonymous Functions)
138+
## Closures (Anonymous Functions)
139139

140140
Where appropriate, closures may be used as an alternative to creating new functions to pass as callbacks. For example:
141141

@@ -151,7 +151,7 @@ $caption = preg_replace_callback(
151151

152152
Closures must not be passed as filter or action callbacks, as they cannot be removed by `remove_action()` / `remove_filter()` (see [#46635](https://core.trac.wordpress.org/ticket/46635 "Improve identifying of non–trivial callbacks in hooks") for a proposal to address this).
153153

154-
### Multiline Function Calls
154+
## Multiline Function Calls
155155

156156
When splitting a function call over multiple lines, each parameter must be on a separate line. Single line inline comments can take up their own line.
157157

@@ -176,13 +176,13 @@ $a = foo(
176176
);
177177
```
178178

179-
### Regular Expressions
179+
## Regular Expressions
180180

181181
Perl compatible regular expressions ([PCRE](https://www.php.net/pcre), `preg_` functions) should be used in preference to their POSIX counterparts. Never use the `/e` switch, use `preg_replace_callback` instead.
182182

183-
It's most convenient to use single-quoted strings for regular expressions since, contrary to double-quoted strings, they have only two metasequences: `\'` and `\\`.
183+
It's most convenient to use single-quoted strings for regular expressions since, contrary to double-quoted strings, they have only two metasequences which need escaping: `\'` and `\\`.
184184

185-
### Opening and Closing PHP Tags
185+
## Opening and Closing PHP Tags
186186

187187
When embedding multi-line PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves.
188188

@@ -217,7 +217,7 @@ if ( $a === $b ) { ?>
217217
<?php }
218218
```
219219

220-
### No Shorthand PHP Tags
220+
## No Shorthand PHP Tags
221221

222222
**Important:** Never use shorthand PHP start tags. Always use full PHP tags.
223223

@@ -235,11 +235,11 @@ Incorrect:
235235
<?= $var ?>
236236
```
237237

238-
### Remove Trailing Spaces
238+
## Remove Trailing Spaces
239239

240-
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.
240+
Remove trailing whitespace at the end of each line. Omitting the closing PHP tag at the end of a file is preferred. If you use the tag, make sure you remove trailing whitespace.
241241

242-
### Space Usage
242+
## Space Usage
243243

244244
Always put spaces after commas, and on both sides of logical, comparison, string and assignment operators.
245245

@@ -252,7 +252,7 @@ $baz . '-5'
252252
$term .= 'X'
253253
```
254254

255-
Put spaces on both sides of the opening and closing parentheses of `if`, `elseif`, `foreach`, `for`, and `switch` blocks.
255+
Put spaces on both sides of the opening and closing parentheses of control structure blocks.
256256

257257
```php
258258
foreach ( $foo as $bar ) { ...
@@ -279,7 +279,7 @@ When performing logical comparisons, do it like so:
279279
if ( ! $foo ) { ...
280280
```
281281

282-
[Type casts](https://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting) must be lowercase. Always prefer the short form of type casts, `(int)` instead of `(integer)` and `(bool)` rather than `(boolean)`. For float casts use `(float)`.:
282+
[Type casts](https://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting) must be lowercase. Always prefer the short form of type casts, `(int)` instead of `(integer)` and `(bool)` rather than `(boolean)`. For float casts use `(float)`, not `(real)` which is [deprecated](https://www.php.net/manual/en/migration74.deprecated.php#migration74.deprecated.core.real) in PHP 7.4, and removed in PHP 8:
283283

284284
```php
285285
foreach ( (array) $foo as $bar ) { ...
@@ -300,7 +300,7 @@ $x = $foo[ $bar ]; // correct
300300
$x = $foo[$bar]; // incorrect
301301
```
302302

303-
In a `switch` block, there must be no space before the colon for a case statement.
303+
In a `switch` block, there must be no space between the `case` condition and the colon.
304304

305305
```php
306306
switch ( $foo ) {
@@ -325,9 +325,9 @@ if ( $foo && ( $bar || $baz ) ) { ...
325325
my_function( ( $x - 1 ) * 5, $y );
326326
```
327327

328-
### Formatting SQL statements
328+
## Formatting SQL statements
329329

330-
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`.
330+
When formatting SQL statements you may break them 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`.
331331

332332
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()`
333333

@@ -340,17 +340,17 @@ $id = some_foo_number(); // data we expect to be an integer, but we're not certa
340340
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) );
341341
```
342342

343-
`%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()`](https://developer.wordpress.org/reference/functions/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.
343+
`%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 it is easy to see at a glance whether something has been escaped or not because it happens right when the query happens.
344344

345345
See [Data Validation](https://developer.wordpress.org/plugins/security/data-validation/) in the Plugin Handbook for further details.
346346

347-
### Database Queries
347+
## Database Queries
348348

349349
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.
350350

351-
If you must touch the database, get in touch with some developers by posting a message to the [wp-hackers mailing list](https://codex.wordpress.org/Mailing_Lists#Hackers). They may want to consider creating a function for the next WordPress version to cover the functionality you wanted.
351+
If you must touch the database, consider creating a [Trac](https://core.trac.wordpress.org/) ticket. There you can discuss the possibility of adding a new function to cover the functionality you wanted, for the next WordPress version.
352352

353-
### Naming Conventions
353+
## Naming Conventions
354354

355355
Use lowercase letters in variable, action/filter, and function names (never `camelCase`). Separate words via underscores. Don't abbreviate variable names unnecessarily; let the code be unambiguous and self-documenting.
356356

@@ -377,21 +377,21 @@ Files should be named descriptively using lowercase letters. Hyphens should sepa
377377
my-plugin-name.php
378378
```
379379

380-
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:
380+
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:
381381

382382
```php
383383
class-wp-error.php
384384
```
385385

386-
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.
386+
This file-naming standard is for all current and new files with classes. There is one exception to this rule for three legacy files: `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.
387387

388-
Files containing template tags in `wp-includes` should have `-template` appended to the end of the name so that they are obvious.
388+
Files containing template tags in the `wp-includes` directory should have `-template` appended to the end of the name so that they are obvious.
389389

390390
```php
391391
general-template.php
392392
```
393393

394-
### Only one object structure (class/interface/trait) should be declared per file
394+
## Only one object structure (class/interface/trait) per file
395395

396396
For instance, if we have a file called `class-example-class.php` it can only contain one class in that file.
397397

@@ -414,7 +414,7 @@ class Example_Class { [...] }
414414
class Example_Class_Extended { [...] }
415415
```
416416

417-
### Self-Explanatory Flag Values for Function Arguments
417+
## Self-Explanatory Flag Values for Function Arguments
418418

419419
Prefer string values to just `true` and `false` when calling functions.
420420

@@ -428,7 +428,8 @@ eat( 'mushrooms', true ); // what does true mean?
428428
eat( 'dogfood', false ); // what does false mean? The opposite of true?
429429
```
430430

431-
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.
431+
PHP only supports named arguments as of PHP 8.0. However, as WordPress currently still supports older PHP versions, we cannot yet use those.
432+
Without 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.
432433

433434
```php
434435
// Correct
@@ -450,7 +451,7 @@ function eat( $what, $args ) {
450451
eat ( 'noodles', array( 'speed' => 'moderate' ) );
451452
```
452453

453-
### Interpolation for Naming Dynamic Hooks
454+
## Interpolation for Naming Dynamic Hooks
454455

455456
Dynamic hooks should be named using interpolation rather than concatenation for readability and discoverability purposes.
456457

@@ -464,7 +465,7 @@ do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
464465

465466
Where possible, dynamic values in tag names should also be as succinct and to the point as possible. `$user_id` is much more self-documenting than, say, `$this->id`.
466467

467-
### Ternary Operator
468+
## Ternary Operator
468469

469470
[Ternary operators](https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) 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.)
470471

@@ -478,7 +479,7 @@ $musictype = ( 'jazz' === $music ) ? 'cool' : 'blah';
478479
// (if field is not empty ) ? (do this) : (else, do this);
479480
```
480481

481-
### Yoda Conditions
482+
## Yoda Conditions
482483

483484
```php
484485
if ( true === $the_force ) {
@@ -494,7 +495,7 @@ A little bizarre, it is, to read. Get used to it, you will.
494495

495496
This applies to `==`, `!=`, `===`, and `!==`. Yoda conditions for `<`, `>`, `<=` or `>=` are significantly more difficult to read and are best avoided.
496497

497-
### Clever Code
498+
## Clever Code
498499

499500
In general, readability is more important than cleverness or brevity.
500501

@@ -568,34 +569,22 @@ switch ( $foo ) {
568569

569570
The `goto` statement must never be used.
570571

571-
The `eval()` construct is _very dangerous_, and is impossible to secure. Additionally, the `create_function()` function, which internally performs an `eval()`, is deprecated in PHP 7.2. Both of these must not be used.
572+
The `eval()` construct is _very dangerous_ and is impossible to secure. Additionally, the `create_function()` function, which internally performs an `eval()`, is deprecated since PHP 7.2 and has been removed in PHP 8.0. Neither of these must be used.
572573

573-
### Error Control Operator `@`
574+
## Error Control Operator `@`
574575

575576
As noted in the [PHP docs](https://www.php.net/manual/en/language.operators.errorcontrol.php):
576577

577-
> 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.
578+
> PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any diagnostic error that might be generated by that expression will be suppressed.
578579
579580
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:
580581

581-
> 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.
582+
> Warning: Prior to PHP 8.0.0, it was possible for the @ operator to disable critical errors that will terminate script execution. For example, prepending @ to a call of a function that did not exist, by being unavailable or mistyped, would cause the script to terminate with no indication as to why.
582583
583-
### Don't `extract()`
584+
## Don't `extract()`
584585

585586
Per [#22400](https://core.trac.wordpress.org/ticket/22400 "Remove all, or at least most, uses of extract() within WordPress"):
586587

587588
> `extract()` is a terrible function that makes code harder to debug and harder to understand. We should discourage it's [sic] use and remove all of our uses of it.
588589
589-
590590
Joseph Scott has [a good write-up of why it's bad](https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/).
591-
592-
## Credits
593-
594-
- PHP standards: [Pear standards](https://pear.php.net/manual/en/standards.php)
595-
596-
### Major Changes
597-
598-
- November 13, 2013: [Braces should always be used, even when they are optional](https://make.wordpress.org/core/2013/11/13/proposed-coding-standards-change-always-require-braces/)
599-
- June 20, 2014: Add (#error-control-operator) to discourage use of the [error control operator]((https://www.php.net/manual/en/language.operators.errorcontrol.php)) (`@`). See [#wordpress-dev](https://irclogs.wordpress.org/chanlog.php?channel=wordpress-dev&amp;day=2014-06-20&amp;sort=asc#m873356).
600-
- 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.
601-
- January 21, 2014: Add section to forbid extract().

0 commit comments

Comments
 (0)