Manual:Coding conventions/PHP

This page describes the coding conventions used within files of the written in PHP. See also the that apply to all program languages, including PHP. If you would like a short checklist to help you review your commits, try using the .

To help developers fix code with an inadequately spacey style, exists a tool called stylize, which do review syntax and add spaces at the relevant places; the tool is also available 2>toollabs:stylize/|with a web interface. It is recommended to run this over files committed to Git.

Rules for PHP_CodeSniffer are also available. For more information, see . The git repository   contains the PHP CodeSniffer settings for MediaWiki code.

Spaces
MediaWiki favors a heavily-spaced style for optimum readability.

Put spaces on either side of binary operators, for example:

Put spaces next to parentheses on the inside, except where the parentheses are empty. Do not put a space following a function name.

Put spaces in brackets when declaring an array, except where the array is empty. Do not put spaces in brackets when accessing array elements.

Control structures such as , , , </>, <tvar|switch></>, as well as the <tvar|catch></> keyword, should be followed by a space:

When type casting, do not use a space within or after the cast operator:

In comments there should be one space between the <tvar|hash></> or <tvar|slash></> character and the comment.

To help developers fix code with an inadequately spacey style, exists a tool called <tvar|1>stylize</>, which add whitespace by PHP conventions automatically. Tool is available by 2>toollabs:stylize/</>|web interface.

Ternary operator
The <tvar|ternary></> can be used profitably if the expressions are very short and obvious:

But if you're considering a multi-line expression with a ternary operator, please consider using an <tvar|if></> block instead. Remember, disk space is cheap, code readability is everything, "if" is English and  is not. If you are using a multi-line ternary expression, the question mark and colon should go at the beginning of the second and third lines and not the end of the first and second (in contrast to MediaWiki's JavaScript convention).

Since MediaWiki requires PHP or later, use of the [<tvar|shorthand>https://secure.php.net/control-structures.if#102060 shorthand</> ternary operator] (<tvar|operator> </>) also known as the elvis operator, introduced in PHP 5.3, is allowed.

Since PHP 7.0 the null coalescing operator is also available and can replace the ternary operator in some use cases. For example, instead of

you could instead write the following:

String literals
Single quotes are preferred in all cases where they are equivalent to double quotes.

Code using single quotes is less error-prone and easier to review, as it can not accidentally contain [<tvar|escapes>https://secure.php.net/language.types.string#language.types.string.syntax.double</> escape sequences] or [<tvar|variables>https://secure.php.net/language.types.string#language.types.string.parsing</> variables]. For example, the regular expression <tvar|regex1></> requires an extra backslash, making it slightly more confusing and error-prone than <tvar|regex2></>. Also for people using US/UK qwerty keyboards, they are easier to type, since it avoids the need to press shift.

However, do not be afraid of using PHP's double-quoted string interpolation feature:

This has slightly better performance characteristics than the equivalent using the concatenation (dot) operator, and it looks nicer too.

Heredoc-style strings are sometimes useful:

Some authors like to use END as the ending token, which is also the name of a PHP function. This leads to IRC conversations like the following:

Functions and parameters
Avoid passing huge numbers of parameters to functions or constructors:

It quickly becomes impossible to remember the order of parameters, and you will inevitably end up having to hardcode all the defaults in callers just to customise a parameter at the end of the list. If you are tempted to code a function like this, consider passing an associative array of named parameters instead.

In general, using boolean parameters is discouraged in functions. In <tvar|example></>, without looking up the documentation for <tvar|example2></>, it is impossible to know what those parameters are meant to indicate. Much better is to either use class constants, and make a generic flag parameter:



Or to make your function accept an array of named parameters:



Try maillist>mailarchive:wikitech-l/2006-November/027618.html</>|not to repurpose variables over the course of a function, and avoid modifying the parameters passed to a function (unless they're passed by reference and that's the whole point of the function, obviously).

Assignment expressions
Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:

Space is cheap, and you're a fast typist, so instead use:

Using assignment in a <tvar|1></> clause used to be legitimate, for iteration:

This is unnecessary in new code; instead use:

C borrowings
The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.

In C, constants are implemented as preprocessor macros and are fast. In PHP, they are implemented by doing a runtime hashtable lookup for the constant name, and are slower than just using a string literal. In most places where you would use an enum or enum-like set of macros in C, you can use string literals in PHP.

PHP has three special literals for which upper-/lower-/mixed-case is insignificant in the language (since PHP 5.1.3), but for which our convention is always lowercase: <tvar|true></>, <tvar|false></> and <tvar|null></>.

Use <tvar|elseif-example></> not <tvar|else-if-example></>. They have [<tvar|phplink>https://secure.php.net/elseif</> subtly different meanings]:

And the latter has poorer performance.

Alternative syntax for control structures
PHP offers an alternative syntax for control structures using colons and keywords such as,  , etc.:

This syntax should be avoided, as it prevents many text editors from automatically matching and folding braces. Braces should be used instead:

Brace placement
See Manual:Coding conventions.

Type declarations in function parameters
Use [<tvar|1>https://secure.php.net/functions.arguments#functions.arguments.type-declaration</> type declarations] and [<tvar|2>https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration</> return type declarations] (type hinting) when applicable.

Note that [<tvar|covariant-rfc>https://wiki.php.net/rfc/covariant-returns-and-contravariant-parameters</> before 7.4] PHP cannot handle type hint restriction / relaxation in subclasses.

Naming
Use lowerCamelCase when naming functions or variables. For example:

Use UpperCamelCase when naming classes: <tvar|1></>.

Use uppercase with underscores for global and class constants: <tvar|2>, </>.

Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.

There are also some prefixes used in different places:

Functions
global functions in extensions, although "in most cases modern style puts hook functions as static methods on a class, leaving few or no raw top-level functions to be so named." (-- brion in Manual_talk:Coding_conventions)
 * ( wiki functions ) – top-level functions, e.g.
 * ( extension functions ) =

Verb phrases are preferred: use <tvar|getreturntext></> instead of <tvar|returntext></>.

Variables

 * – global variables, e.g. <tvar|wgversion></>, <tvar|wgtitle></>. Always use this for new globals, so that it's easy to spot missing "" declarations.  In extensions, the extension name should be used as a namespace delimiter.  For example,, not.


 * Global declarations should be at the beginning of a function so dependencies can be determined without having to read the whole function.

It is common to work with an instance of the <tvar|database> </> class; we have a naming convention for these which helps keep track of the nature of the server to which we are connected. This is of particular importance in replicated environments, such as Wikimedia and other large wikis; in development environments, there is usually no difference between the two types, which can conceal subtle errors.


 * – a  object for writing (a master connection)
 * – a  object for non-concurrency-sensitive reading (this may be a read-only slave, slightly behind master state, so don't ever try to write to the database with it, or get an "authoritative" answer to important queries like permissions and block status)

The following may be seen in old code but are discouraged in new code:


 * – Session variables, e.g.
 * – Cookie variables, e.g.
 * – Post variables (submitted via form fields), e.g.
 * – object member variables: . This is discouraged in new code, but try to stay consistent within a class.

The <tvar|empty></> function should only be used when you want to suppress errors. Otherwise just use  (boolean conversion).

Common use case: Optional boolean configuration keys that default to false.
 * essentially does.


 * Beware of boolean conversion pitfalls.

If only intending to test for "empty" values (e.g. false, zero, empty array, etc.), use.
 * It suppresses errors about undefined properties and variables. If only intending to test for undefined, use.

Do not use <tvar|isset></> to test for <tvar|null> </>. Using <tvar|isset></> in this situation could introduce errors by hiding misspelled variable names. Instead, use <tvar|comparison></>.

Boolean conversion

 * Do not use  or <tvar|empty></> to test if a string or array is empty, because PHP considers    to be falsy – but   is a valid title and valid user name in MediaWiki. Use   or   instead.
 * Study the rules for [<tvar|conversions>https://secure.php.net/language.types.boolean#language.types.boolean.casting</> conversion to boolean]. Be careful when converting strings to boolean.

Other

 * [<tvar|phpplus>https://secure.php.net/operators.array</> Array plus] does not renumber the keys of numerically-indexed arrays, so . If you want keys to be renumbered, use :


 * Make sure you have set to  .  This will notify you of undefined variables and other subtle gotchas that stock PHP will ignore.  See also <tvar|1></>.


 * When working in a pure PHP file (e.g. not an HTML template), omit any trailing  tags. These tags often cause issues with trailing white-space and "headers already sent" error messages (cf. 17642 and http://news.php.net/php.general/280796). It is conventional in version control for files to have a new line at end-of-file (which editors may add automatically), which would then trigger this error.


 * Do not use the syntax introduced in 5.3.  PHP may have introduced the feature, but that does not mean we should use it.


 * Do not pass by reference when traversing an array unless you have to. Even then, be aware of the consequences. (See http://www.king-foo.be/2010/10/php-quirks-passing-an-array-by-reference/)


 * PHP lets you declare static variables even within a non-static method of a class. This has led to subtle bugs in some cases, as the variables are shared between instances. Where you would not use a  property, do not use a static variable either.

Equality operators
Be careful with double-equals comparison operators.

Triple-equals is generally more intuitive and should be preferred unless you have a reason to use double-equals.


 * <tvar|1></> is true (!)


 * <tvar|1></> is true (!)


 * <tvar|1></> is false


 * To check if two scalars that are supposed to be numeric are equal, use <tvar|1> </>, e.g. <tvar|2></> is true.


 * To check if two variables are both of type 'string' and are the same sequence of characters, use <tvar|1> </>, e.g. <tvar|2></> is false.

JSON number precision
JSON uses JavaScript's type system, so all numbers are represented as 64bit IEEE floating point numbers.

This means that numbers lose precision when getting bigger, to the point where some whole numbers become indistinguishable: Numbers beyond 2^52 will have a precision worse than ±0.5, so a large integer may end up changing to a different integer.

To avoid this issue, represent potentially large integers as strings in JSON.

Don't use built in serialization
PHP's built in serialization mechanism (the <tvar|1> </> and <tvar|2> </> functions) should not be used for data stored (or read from) outside of the current process.

Use JSON based serialization instead (however, beware the 1>#JSON number precision</>|pitfalls).

This is policy established by 1>Requests for Comment</>|RFC <tvar|2>T161647</>.

The reason is twofold: (1) data serialized with this mechanism cannot reliably be unserialized with a later version of the same class.

And (2) crafted serialized data can be used to execute malicious code, posing a serious security risk.

Sometimes, your code will not control the serialization mechanism, but will be using some library or driver that uses it internally.

In such cases, steps should be taken to mitigate risk.

The first issue mentioned above can be mitigated by converting any data to arrays or plain anonymous objects before serialization.

The second issue can perhaps be mitigated using the whitelisting feature PHP 7 introduces for unserialization.

Comments and documentation
It is essential that your code be well documented so that other developers and bug fixers can easily navigate the logic of your code.

New classes, methods, and member variables should include comments providing brief descriptions of their functionality (unless it is obvious), even if private.

In addition, all new methods should document their parameters and return values.

We use the Doxygen documentation style (it is very similar to PHPDoc for the subset that we use) to produce auto-generated documentation from code comments (see Manual:mwdocgen.php).

Begin a block of Doxygen comments with, instead of the Qt-style formatting.

Doxygen structural commands start with.

(Use  rather than   as the escape character – both styles work in Doxygen, but for backwards and future compatibility MediaWiki has chosen the   style.)

They organize the generated documentation (using ) and identify authors (using   tags).

They describe a function or method, the parameters it takes (using <tvar|param> </>), and what the function returns (using <tvar|return> </>). The format for parameters is: @param type $paramName Description of parameter

If a parameter can be of multiple types, separate them with the pipe '|' character, for example:

Continue sentences belonging to an annotation on the next line, indented with one additional space.

For every public interface (method, class, variable, whatever) you add or change, provide a  tag, so people extending the code via this interface know they are breaking compatibility with older versions of the code.

FIXME usually means something is bad or broken. TODO means that improvements are needed; it does not necessarily mean that the person adding the comment is going to do it. HACK means that a quick but inelegant, awkward or otherwise suboptimal solution to an immediate problem was made, and that eventually a more thorough rewrite of the code should be done.

Source file headers
In order to be compliant with most licenses you should have something similar to the following (specific to GPLv2 applications) at the top of every source file.

Doxygen tags
We use the following annotations which Doxygen recognizes. Use them in this order, for consistency:

File level:
 * @file
 * @ingroup
 * @author

Class, class member, or global member:


 * @todo
 * @var
 * @deprecated
 * @class
 * @see
 * @since
 * @param
 * @return
 * @throws
 * @private

Test annotations
In tests, we use the following annotations among others. These aren't merely documentation, they mean something to PHPUnit and affect test execution.


 * @depends
 * @group
 * @covers
 * @dataProvider
 * @expectedException
 * @expectedExceptionMessage

Integration
There are a few pieces of code in the MediaWiki codebase which are intended to be standalone and easily portable to other applications.

While some of these now exist as libraries>Special:MyLanguage/Manual:Developing libraries</>|separate libraries, others remain within the MediaWiki source tree (e.g. the files in <tvar|libs> </>).

Apart from these, code should be integrated into the rest of the MediaWiki environment, and should allow other areas of the codebase to integrate with it in return.

Visibility
Make methods public/protected/private (think what makes sense). Don't just make everything public!

Global objects
Do not access the PHP superglobals <tvar|get></>, <tvar|post></>, etc, directly; mailist>mailarchive:wikitech-l/2007-February/030029.html</>|use <tvar|example>></> instead; there are various functions depending on what type of value you want.You can get a <tvar|webrequest></> from the nearest <tvar|requestcontext></>, or if absolutely necessary <tvar|fallback></>. Equally, do not access <tvar|server></> directly; use <tvar|getip></> if you want to get the IP address of the current user.

Static methods and properties
Static methods and properties can be used in PHP, but care should be taken when inheriting to distinguish between the <tvar|1> </> and <tvar|2> </> keywords.

<tvar|1> </> will always refer to the class in which it was defined, whereas <tvar|2> </> will refer to the particular sub-class invoking it.

See the PHP documentation on [<tvar|url>https://php.net/language.oop5.late-static-bindings</> Late Static Bindings] for more details.

Classes
Encapsulate your code in an object-oriented class, or add functionality to existing classes; do not add new global functions or variables. Try to be mindful of the distinction between 'backend' classes, which represent entities in the database (eg,  ,  , etc), and 'frontend' classes, which represent pages or interfaces visible to the user ( ,  ,  , etc. Even if your code is not obviously object-oriented, you can put it in a static class (eg   or  ).

As a holdover from PHP 4's lack of private class members and methods, older code will be marked with comments such as <tvar|private></> to indicate the intention; respect this as if it were enforced by the interpreter.

maillist>mailarchive:wikitech-l/2007-February/029435.html</>|Mark new code with proper visibility modifiers, including <tvar|public></> if appropriate, but do not add visibility to existing code without first checking, testing and refactoring as required. It's generally a good idea to avoid visibility changes unless you're making changes to the function which would break old uses of it anyway.

Error handling
Don't suppress errors with PHP's [<tvar|at>https://secure.php.net/operators.errorcontrol</>  operator], for r39789>Special:Code/MediaWiki/39789#c2650</>|any reason ever. It's broken when <tvar|estrict> </> is enabled and it causes an unlogged, unexplained error if there is a fatal, which is hard to support.

The proper method of handling errors is to actually handle the errors.

For example, if you are thinking of using an error suppression operator to suppress an invalid array index warning, you should instead perform an <tvar|isset></> check on the array index before trying to access it.

When possible, always prevent PHP errors rather than catching and handling them afterwards.

It makes the code more understandable and avoids dealing with slow error suppression methods.

If and only if there is a situation where you are expecting an unavoidable PHP warning, you may use <tvar|suppress> </> and <tvar|restore> </> from the at-ease library instead of the <tvar|at> </> operator. This is for cases where:


 * 1) It is impossible to anticipate the error that is about to occur; and
 * 2) You are planning on handling the error in an appropriate manner after it occurs.

An example of this is opening a file with <tvar|fopen> </>.

You can anticipate the error by calling  and , but it is possible the file will have been deleted in between the check and the actual   call.

In this case, your code should be ready to handle the case that the file will fail to open, and you can use <tvar|1> </> to prevent PHP from being noisy.

Note that using <tvar|suppress> </> and <tvar|restore> </> are slow.

They are much slower than using the <tvar|at> </> operator, since it involves at least four function calls and reference counting, rather than just an opcode.

When your code encounters a sudden error, you should throw an exception rather than using PHP's <tvar|trigger></>.

The exception handler will display this as nicely as possible to the end user and wiki administrator, and also provides a stack trace to developers.

Don't throw an instance of Exception itself, but instead a subclass of it.

Exceptions that indicate programming errors should be one of the [<tvar|spl>https://secure.php.net/spl.exceptions</> exceptions that ship with PHP] or a more specific subclass, while exceptions that indicate errors that are relevant to the end user should be an [<tvar|errorpagerror>https://doc.wikimedia.org/mediawiki-core/master/php/classErrorPageError.html</> ErrorPageError] or one of its subclasses.