Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Tip
titleCorrect
Code Block
languagephp
if ($foo > $bar) {
    echo "foo is greater";
}
else {
    echo "bar is greater";
}

$i = 5;
do {
    echo $i--;
} while ($i > 0);

Classes

Declaration

Class names should be CamelCased. Only a single class should appear in a file. Class file names should correlate to the class name, be lowercase, and use underscores to separate words. Class constructors should be named using the __construct() magic method.

Warning
titleIncorrect
Code Block
languagephp
titlemy_class.php
linenumberstrue
<?php
// Class name starts with a lower case letter
class myClass {
    // Constructor should be named __construct()
    public function myClass() {
    }
}
?>
Tip
titleCorrect
Code Block
languagephp
titlemy_class.php
linenumberstrue
<?php 
class MyClass {
    public function __construct() {
    }
}
?>

Member Variables

All member variables should be declared at the top of the class, before any methods are declared. Variables must always declare their visibility using public, private, or protected.

Warning
titleIncorrect
Code Block
languagephp
linenumberstrue
<?php
class MyClass {
    // Can not use var, must use public, private, or protected
    var $foo;

    public function __construct() {
    }
    
    // Must be declared at the top of the class
    private $bar = "baz";
}
?>
Tip
titleCorrect
Code Block
languagephp
linenumberstrue
<?php
class MyClass {
    public $foo;
    private $bar = "baz";

    public function __construct() {
    }
}
?>

 

Methods

Method names should begin with a lowercase letter and be camelCased. Type hinting should be used whenever possible, but must conform to PHP 5.1 syntax (i.e. only objects and arrays may be defined using type hints).

...