You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Copy file name to clipboardExpand all lines: wordpress-coding-standards/php.md
+47-58Lines changed: 47 additions & 58 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,14 @@
1
1
# PHP Coding Standards
2
2
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.
4
4
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.
6
6
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.
8
8
9
-
## PHP
9
+
Also see the [PHP Inline Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/php/) for further guidelines.
10
10
11
-
###Single and Double Quotes
11
+
## Single and Double Quotes
12
12
13
13
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:
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.
21
21
22
-
###Indentation
22
+
## Indentation
23
23
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.
25
25
26
26
Exception: if you have a block of code that would be more readable if things are aligned, use spaces:
27
27
@@ -59,7 +59,7 @@ $my_array = array(
59
59
);
60
60
```
61
61
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.
63
63
64
64
```php
65
65
switch ( $type ) {
@@ -74,7 +74,7 @@ switch ( $type ) {
74
74
75
75
**Rule of thumb:** Tabs should be used at the beginning of the line for indentation, while spaces can be used mid-line for alignment.
76
76
77
-
###Brace Style
77
+
## Brace Style
78
78
79
79
Braces shall be used for all blocks in the style shown here:
80
80
@@ -111,7 +111,7 @@ foreach ( $items as $item ) {
111
111
}
112
112
```
113
113
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:
115
115
116
116
```php
117
117
<?php if ( have_posts() ) : ?>
@@ -125,17 +125,17 @@ Note that requiring the use of braces just means that _single-statement inline c
125
125
<?php endif; ?>
126
126
```
127
127
128
-
###Use `elseif`, not `else if`
128
+
## Use `elseif`, not `else if`
129
129
130
130
`else if` is not compatible with the colon syntax for `if|elseif` blocks. For this reason, use `elseif` for conditionals.
131
131
132
-
###Declaring Arrays
132
+
## Declaring Arrays
133
133
134
134
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.
135
135
136
136
Arrays must be declared using long array syntax.
137
137
138
-
###Closures (Anonymous Functions)
138
+
## Closures (Anonymous Functions)
139
139
140
140
Where appropriate, closures may be used as an alternative to creating new functions to pass as callbacks. For example:
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).
153
153
154
-
###Multiline Function Calls
154
+
## Multiline Function Calls
155
155
156
156
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.
157
157
@@ -176,13 +176,13 @@ $a = foo(
176
176
);
177
177
```
178
178
179
-
###Regular Expressions
179
+
## Regular Expressions
180
180
181
181
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.
182
182
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 `\\`.
184
184
185
-
###Opening and Closing PHP Tags
185
+
## Opening and Closing PHP Tags
186
186
187
187
When embedding multi-line PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves.
188
188
@@ -217,7 +217,7 @@ if ( $a === $b ) { ?>
217
217
<?php }
218
218
```
219
219
220
-
###No Shorthand PHP Tags
220
+
## No Shorthand PHP Tags
221
221
222
222
**Important:** Never use shorthand PHP start tags. Always use full PHP tags.
223
223
@@ -235,11 +235,11 @@ Incorrect:
235
235
<?= $var ?>
236
236
```
237
237
238
-
###Remove Trailing Spaces
238
+
## Remove Trailing Spaces
239
239
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.
241
241
242
-
###Space Usage
242
+
## Space Usage
243
243
244
244
Always put spaces after commas, and on both sides of logical, comparison, string and assignment operators.
245
245
@@ -252,7 +252,7 @@ $baz . '-5'
252
252
$term .= 'X'
253
253
```
254
254
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.
256
256
257
257
```php
258
258
foreach ( $foo as $bar ) { ...
@@ -279,7 +279,7 @@ When performing logical comparisons, do it like so:
279
279
if ( ! $foo ) { ...
280
280
```
281
281
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:
283
283
284
284
```php
285
285
foreach ( (array) $foo as $bar ) { ...
@@ -300,7 +300,7 @@ $x = $foo[ $bar ]; // correct
300
300
$x = $foo[$bar]; // incorrect
301
301
```
302
302
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.
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`.
331
331
332
332
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()`
333
333
@@ -340,17 +340,17 @@ $id = some_foo_number(); // data we expect to be an integer, but we're not certa
340
340
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) );
341
341
```
342
342
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.
344
344
345
345
See [Data Validation](https://developer.wordpress.org/plugins/security/data-validation/) in the Plugin Handbook for further details.
346
346
347
-
###Database Queries
347
+
## Database Queries
348
348
349
349
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.
350
350
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.
352
352
353
-
###Naming Conventions
353
+
## Naming Conventions
354
354
355
355
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.
356
356
@@ -377,21 +377,21 @@ Files should be named descriptively using lowercase letters. Hyphens should sepa
377
377
my-plugin-name.php
378
378
```
379
379
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:
381
381
382
382
```php
383
383
class-wp-error.php
384
384
```
385
385
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.
387
387
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.
389
389
390
390
```php
391
391
general-template.php
392
392
```
393
393
394
-
###Only one object structure (class/interface/trait) should be declared per file
394
+
## Only one object structure (class/interface/trait) per file
395
395
396
396
For instance, if we have a file called `class-example-class.php` it can only contain one class in that file.
397
397
@@ -414,7 +414,7 @@ class Example_Class { [...] }
414
414
class Example_Class_Extended { [...] }
415
415
```
416
416
417
-
###Self-Explanatory Flag Values for Function Arguments
417
+
## Self-Explanatory Flag Values for Function Arguments
418
418
419
419
Prefer string values to just `true` and `false` when calling functions.
420
420
@@ -428,7 +428,8 @@ eat( 'mushrooms', true ); // what does true mean?
428
428
eat( 'dogfood', false ); // what does false mean? The opposite of true?
429
429
```
430
430
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.
432
433
433
434
```php
434
435
// Correct
@@ -450,7 +451,7 @@ function eat( $what, $args ) {
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`.
466
467
467
-
###Ternary Operator
468
+
## Ternary Operator
468
469
469
470
[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.)
// (if field is not empty ) ? (do this) : (else, do this);
479
480
```
480
481
481
-
###Yoda Conditions
482
+
## Yoda Conditions
482
483
483
484
```php
484
485
if ( true === $the_force ) {
@@ -494,7 +495,7 @@ A little bizarre, it is, to read. Get used to it, you will.
494
495
495
496
This applies to `==`, `!=`, `===`, and `!==`. Yoda conditions for `<`, `>`, `<=` or `>=` are significantly more difficult to read and are best avoided.
496
497
497
-
###Clever Code
498
+
## Clever Code
498
499
499
500
In general, readability is more important than cleverness or brevity.
500
501
@@ -568,34 +569,22 @@ switch ( $foo ) {
568
569
569
570
The `goto` statement must never be used.
570
571
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.
572
573
573
-
###Error Control Operator `@`
574
+
## Error Control Operator `@`
574
575
575
576
As noted in the [PHP docs](https://www.php.net/manual/en/language.operators.errorcontrol.php):
576
577
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.
578
579
579
580
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:
580
581
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.
582
583
583
-
###Don't `extract()`
584
+
## Don't `extract()`
584
585
585
586
Per [#22400](https://core.trac.wordpress.org/ticket/22400"Remove all, or at least most, uses of extract() within WordPress"):
586
587
587
588
> `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.
588
589
589
-
590
590
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/).
- 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&day=2014-06-20&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