PHP Coding Style

File Formatting

  • New Lines
    • Use unix file format
  • Indentation
    • Use tabs, not spaces.
  • File end
    • Do not include the closing PHP tag (see PHP Tags below for more details)
    • Make sure there is 1+ empty lines (for svn)

Variable Naming

  • Camel Case
  • Variables containing objects are capitalized
  • Arrays pluralized
  • Global variables prefixed with 'wg'
$message = 'Hello, world';
$messages = array();
$coolStuffHere = 7;
$Message = new Message(); 
$wgGlobalMessages = array();

Object & Method Naming

  • Camel Case
  • Global functions prefixed with 'wf'
  • Type hinting is not required but good to see
/* Functions start lowercased */
function reallyGreatFunction()
{
}

/* Functions in the global namespace are prefixed with 'wf' */
function wfReallyGreatFunction() 
{ 

}

/* Objects start uppercased */
class FooBar
{
 	private $variable;
 	public function FooBar()
 	{
 	}

 	/* Small functions can be one lined */
 	public function getVar() { return $this->variable; }
	
	protected function doSomething()
	{
	}
}

/* Type hinting example */
class ZooFar
{
    public function operateOn(DekiUser $User, DekiRole $Role, DekiAuthService $Service)
    {
        // do stuff
    }
}

/* Common naming conventions */
class MooDar
{
    /* Common for singletons */
    public static getInstance() {}

    /* Common for session specific, singleton special case */
    public static getCurrent() {}

    /* Site wide method */
    public static getSiteXXXX(){}

}

Comments

  • Use JavaDoc style comments. I'm currently creating documentation with Doxygen which supports JavaDoc styles comments.
  • Click here for a list of supported @tags.
  • Don't use # (hash) comments
  • Always specify types on params when dealing with objects. ZendStudio picks up types from JavaDoc which enables intellisense.
    • The bare minimum comments for all functions should include param details.

TODO: How to document the author? @note, @author??? Ideas?

  • RoyK: Don't think author is necessary; we're not writing complex methods :)
/**
 * User Creation
 * @param string $firstName the user's first name
 * @param string $lastName the user's last name
 * @return int $userId user's new id
 *
 * @note Creates a new user
 */
private function userCreate($firstName, $lastName)
{
}

If Statements

Short Block

// CORRECT
if ($foo > $bar)
{
}

// INCORRECT
if ($foo == $bar)
 	//code here for the true case
if ($foo == $bar)
 	//code here for the true case

Long Block

if ($foo > $bar)
{
}
else if ($foo == $bar)
{
}
else
{
}

Deep Nested Conditionals

// CORRECT: Add spaces to make the conditional easier to read
if ( ($a > $b) || ($c == $d) && ($e <= $f) ^ ( ( (!$g) && ($h < $i) ) || ($j) ) )
{
}
else if ( ($a== $b) && ($c == $d) )
{
}

// INCORRECT
if (($a>$b)||($c==$d)&&($e<=$f)^(((!$g)&&($h<$i))||($j)))
{
}
else if (($a==$b)&&($c==$d)
{
}

Ternary Operator

Usage of parentheses within the operation is up to the coder's discretion.

echo $foo == $bar ? 'OK' : 'Nope';

echo $cond ?
    'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt' :
    'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.';
$var = $foo > $bar ? $baz : 28;
$seven = (1 < 3) ? 7 : 6;
return ($a ^ $b) ? 1 : -1;

 

Strings

  • Use single quotes except when dealing with special characters like \n, \t, \r, etc.
  • Add spaces between the dot concatenation operator.
  • Don't embed PHP variables within double quotes. (shouldn't be using double quotes)
  • Break up long multiline strings so they wrap without word wrap enabled.
    • Guerric: I actually prefer using echo without parens. Less verbose. Also, there is a speed up benefit when outputting strings in succession. In order to use this method the args are specified without parens.
      • echo $var . ' ' . $two . ' ' . $three;
      • echo $var, ' ', $two, ' ', $three;
echo('Foo' . 'Bar');
echo('Foo'. $baz .'Bar');
echo('Foo' . $baz . 'Bar');

// Special character usage
echo("\t" . 'Foo Bar' . "\n");

// Multiline strings
echo('<a href="'. $url .'">'. 'Page ' . $pageName .'</a>'.
     ' More long text here...' . "\n");

// Alternate method, printf
printf('<a href="%s">Page %s</a>' . "\n", $url, $pageName);

// DO NOT do this
echo 'Foo'.$baz.'Bar';
echo "Foo".$baz."Bar";
echo "Foo{$baz}Bar";
echo '<a href="'.$url.'">'.'Page '.$pageName.'</a> More long text here...'."\n";

 

PHP Tags

  • Never use short tag notation
  • Always escape PHP blocks with <?php
  • For PHP files, the closing tag ("?>") should be omitted. It is perfectly legal, and prevents errant whitespaces from being output. 

   

//CORRECT
$string = 'Hello, world';
<?php echo($string); ?>
<?php echo('Hello, world'); ?>

//INCORRECT
<? echo($string); ?>
<?=$string?>

Sample PHP file

<?php
class SomethingUseful
{

}
// notice no closing php tag

 

 Arrays

  • Should be indented properly for readability, see the sample below
$arr = array(
    'something' => 1,
    'two' => array(
        'nested'
    )
);

  

Tag page
You must login to post a comment.