Function Definitions

Function declarations follow the "K&R style":

<?php
function fooFunction($arg1$arg2 '')
{
    if (
condition) {
        
statement;
    }
    return 
$val;
}
?>

Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate. Here is a slightly longer example:

<?php
function connect(&$dsn$persistent false)
{
    if (
is_array($dsn)) {
        
$dsninfo = &$dsn;
    } else {
        
$dsninfo DB::parseDSN($dsn);
    }

    if (!
$dsninfo || !$dsninfo['phptype']) {
        return 
$this->raiseError();
    }

    return 
true;
}
?>

Split function definitions onto several lines

Functions with many parameters may need to be split onto several lines to keep the 80 characters/line limit. The first parameters may be put onto the same line as the function name if there is enough space. Subsequent parameters on following lines are to be indented 4 spaces. The closing parenthesis and the opening brace are to be put onto the next line, on the same indentation level as the "function" keyword.

<?php

function someFunctionWithAVeryLongName($firstParameter 'something'$secondParameter 'booooo',
    
$third null$fourthParameter false$fifthParameter 123.12,
    
$sixthParam true
) {
    
//....
?>
Class Definitions (Previous) Arrays (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

Note by: Mike
Note to previous post: the Allman style is not only used for functions but also for class definitions.
Note by: pear at alan hogan dot com
Allman style is defined here for those unfamiliar with it:
http://en.wikipedia.org/wiki/Indent_style

Please note that the PEAR coding standards *do not* follow Allman style for *control structures*, only for functions.
Note by: pear at alan hogan dot com
Again according to Wikipedia, it would seem that PEAR, in fact, advocates K&R style:

function foo ()
{
//do stuff();
}

while (true) {
if (true ) {
//x..
}
}

It should be noted that both Allman and K&R agree on how to format function definitions.