PHP代码风格和最佳实践
PHP代码风格和最佳实践
Coding Style
1. Class name must CamelCaps 1. brace another line 2. Method 1. StudlyCaps 2. camelCaps 3. under_score
1. Control structure keywords MUST have one space after them; method and function calls MUST NOT. 2. Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
Function
1. Allman style
Variable
1. camelCaps
Best Practice
Storing passowrd use password_hash/password_verify function
connect mysql use PDO class
Auto-loading class use spl_autoload_register() function
Single vs. double quotes from a performance perspective
It doesn’t really matter. awlays use same styleUse define() unless readability, class constants, or micro-optimization are concerns.
PHP and Memcached If you need a distributed cache, use the Memcached client library. Otherwise, use APCu.
PHP and regex Use the PCRE (preg_*) family of functions.
Sending email Use PHPMailer.
Validating email addresses Use the filter_var() function.
Sanitizing HTML input and output Use the htmlentities() function for simple sanitization and the HTML Purifier library for complex sanitization.
Working with dates and times Use the DateTime class.
Checking if a value is null or false Use the === operator to check for null and boolean false values.
Eaxmple
<?php
namespace Vendor\Package;
use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;
class Foo extends Bar implements FooInterface
{
public function sampleFunction($a, $b = null)
{
if ($a === $b) {
bar();
} elseif ($a > $b) {
$foo->bar($arg1);
} else {
BazClass::bar($arg2, $arg3);
}
}
final public static function bar()
{
// 方法的内容
}
}
<?php
switch ($expr) {
case 0:
echo 'First case, with a break';
break;
case 1:
echo 'Second case, which falls through';
// no break
case 2:
case 3:
case 4:
echo 'Third case, return instead of break';
return;
default:
echo 'Default case';
break;
}
<?php
for ($i = 0; $i < 10; $i++) {
// for body
}
<?php
foreach ($iterable as $key => $value) {
// foreach body
}
Reference: