Appearance
PHP 速记表
基础语法
Hello World & 注释
<?php// Hello Worldecho "Hello, World!";// 单行注释# 单行注释(shell 风格)/* 多行注释 可以换行 *//** * PHPDoc 文档注释 * @param string $name * @return string */?>输入输出
<?php// 输出echo "Hello, World!";print "Hello, World!";printf("Name: %s, Age: %d\n", "Alice", 25);// 命令行输入$name = readline("Enter your name: ");echo "Hello, " . $name . "!\n";// Web 表单输入$name = $_POST['name'] ?? '';$age = $_GET['age'] ?? 0;?>变量与常量
变量声明
<?php$name = "Alice";$age = 25;$pi = 3.14;$isValid = true;// 变量变量$var = "name";$$var = "Bob"; // $name = "Bob"常量
define('MAX', 100);const API_KEY = "secret"; // PHP 5.3+// 魔术常量__FILE__ // 文件路径__LINE__ // 行号__DIR__ // 目录__FUNCTION__ // 函数名__CLASS__ // 类名__METHOD__ // 方法名作用域
$globalVar = "global"; // 全局作用域function example() { global $globalVar; // 使用全局变量 $localVar = "local"; // 局部作用域 static $staticVar = 0; // 静态变量 $staticVar++;}数据类型
标量类型
// 整数$int = 42;$hex = 0x1A;$octal = 0123;$binary = 0b1010;// 浮点数$float = 3.14;$scientific = 1.2e3;// 字符串$str = "hello";$str = 'world';// 布尔$bool = true;$bool = false复合类型
// 数组$arr = [1, 2, 3];$arr = array(1, 2, 3);// 对象$obj = new stdClass();$obj->name = "Alice";// 资源$file = fopen("file.txt", "r");// NULL$null = null;类型声明
PHP 7+
function add(int $a, int $b): int { return $a + $b;}function greet(string $name): void { echo "Hello, $name";}// PHP 7.4+ 属性类型class User { public string $name; public int $age;}类型转换
(int)$value(float)$value(string)$value(bool)$value(array)$value(object)$valueintval($value)floatval($value)strval($value)运算符
算术运算符
+ - * / % **++ --比较运算符
== != <> // 相等=== !== // 全等> < >= <=<=> // 太空船运算符 (PHP 7+)逻辑运算符
&& and|| or! notxor字符串运算符
. // 拼接.= // 拼接赋值赋值运算符
= += -= *= /= %= **=.= &= |= ^= <<= >>=Null 运算符
PHP 7+
// Null 合并$name = $_GET['name'] ?? 'default';// Null 安全 (PHP 8+)$name = $user?->profile?->name;字符串
字符串创建
$str = "hello";$str = 'world';// Heredoc$text = <<<EOTMulti-linestringEOT;// Nowdoc (PHP 5.3+)$text = <<<'EOT'No variableinterpolationEOT;字符串插值
$name = "Alice";$age = 25;echo "Name: $name, Age: $age";echo "Name: {$name}, Age: {$age}";echo 'Name: ' . $name . ', Age: ' . $age;字符串函数
strlen($str)strtoupper($str)strtolower($str)ucfirst($str)ucwords($str)trim($str)ltrim($str)rtrim($str)substr($str, 0, 5)strpos($str, 'sub')str_replace('old', 'new', $str)str_contains($str, 'sub') // PHP 8+str_starts_with($str, 'pre') // PHP 8+str_ends_with($str, 'fix') // PHP 8+字符串分割与拼接
$parts = explode(' ', $str);$joined = implode('-', $parts);$result = join(', ', $arr);正则表达式
preg_match('/pattern/', $str, $matches);preg_match_all('/pattern/', $str, $matches);preg_replace('/old/', 'new', $str);preg_split('/\s+/', $str);数组
数组创建
$arr = [1, 2, 3, 4, 5];$arr = array(1, 2, 3);// 关联数组$person = [ 'name' => 'Alice', 'age' => 25];数组操作
array_push($arr, 6);$arr[] = 7;array_pop($arr);array_shift($arr);array_unshift($arr, 0);count($arr);in_array(5, $arr);array_key_exists('key', $arr);数组函数
array_map(fn($x) => $x * 2, $arr);array_filter($arr, fn($x) => $x > 5);array_reduce($arr, fn($acc, $x) => $acc + $x, 0);array_slice($arr, 1, 3);array_merge($arr1, $arr2);array_unique($arr);sort($arr);rsort($arr);asort($arr); // 保持键关联ksort($arr); // 按键排序遍历数组
foreach ($arr as $value) { echo $value;}foreach ($arr as $key => $value) { echo "$key: $value";}// 引用修改foreach ($arr as &$value) { $value *= 2;}数组解构
PHP 7.1+
[$a, $b] = [1, 2];['name' => $name, 'age' => $age] = $person;控制流
if / else
if ($condition) { // 执行} elseif ($other) { // 执行} else { // 执行}// 三元运算符$result = $condition ? 'yes' : 'no';switch
switch ($value) { case 1: echo "one"; break; case 2: case 3: echo "two or three"; break; default: echo "other";}match
PHP 8+
$result = match($status) { 'success' => 'Operation successful', 'error' => 'Operation failed', default => 'Unknown status'};for 循环
for ($i = 0; $i < 10; $i++) { echo $i;}foreach ($arr as $value) { echo $value;}foreach ($arr as $key => $value) { echo "$key: $value";}while 循环
while ($condition) { // 执行}do { // 至少执行一次} while ($condition);跳转语句
break; // 退出循环continue; // 跳过本次return $value; // 返回值goto label; // 跳转函数
函数定义
function add($a, $b) { return $a + $b;}// 默认参数function greet($name = "Guest") { return "Hello, $name";}// 类型声明 (PHP 7+)function sum(int $a, int $b): int { return $a + $b;}箭头函数
PHP 7.4+
$square = fn($x) => $x * $x;$add = fn($a, $b) => $a + $b;// 自动捕获外部变量$factor = 2;$multiply = fn($x) => $x * $factor;匿名函数
$greet = function($name) { return "Hello, $name";};// use 捕获外部变量$multiplier = 2;$multiply = function($x) use ($multiplier) { return $x * $multiplier;};可变参数
function sum(...$nums) { return array_sum($nums);}$result = sum(1, 2, 3, 4, 5);// 解包参数$arr = [1, 2, 3];sum(...$arr);命名参数
PHP 8+
function createUser($name, $email, $age) { // ...}createUser( name: 'Alice', age: 25, email: 'alice@example.com');面向对象
类定义
class Person { private $name; protected $age; public $email; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function greet() { return "Hello, I'm {$this->name}"; } public static function species() { return "Human"; }}$person = new Person("Alice", 25);构造器属性提升
PHP 8+
class Person { public function __construct( public string $name, public int $age, private string $email = "" ) {}}$person = new Person("Alice", 25);echo $person->name;继承
class Student extends Person { private $major; public function __construct($name, $age, $major) { parent::__construct($name, $age); $this->major = $major; } public function study() { echo "Studying $this->major"; }}接口与抽象类
interface Drawable { public function draw();}abstract class Shape { abstract public function area(); public function describe() { echo "This is a shape"; }}class Circle extends Shape implements Drawable { public function area() { return 3.14 * $this->radius ** 2; } public function draw() { echo "Drawing circle"; }}Trait
trait Logger { public function log($message) { echo "[LOG] $message"; }}class User { use Logger;}$user = new User();$user->log("User created");魔术方法
class MyClass { public function __construct() {} public function __destruct() {} public function __toString() {} public function __get($name) {} public function __set($name, $value) {} public function __call($name, $args) {} public function __invoke() {}}Enum
PHP 8.1+
enum Status { case Pending; case Approved; case Rejected;}$status = Status::Pending;// Backed Enumenum HttpStatus: int { case OK = 200; case NotFound = 404; case ServerError = 500;}错误处理
try/catch
try { throw new Exception("Something went wrong");} catch (Exception $e) { echo "Error: " . $e->getMessage();} finally { echo "Always executed";}多重捕获
PHP 7.1+
try { // 可能抛出异常} catch (RuntimeException | InvalidArgumentException $e) { echo "Error: " . $e->getMessage();}自定义异常
class ValidationException extends Exception { public function __construct($message) { parent::__construct($message); }}throw new ValidationException("Invalid input");文件操作
读取文件
// 读取全部$content = file_get_contents('file.txt');// 读取行数组$lines = file('file.txt');// 逐行读取$handle = fopen('file.txt', 'r');while (($line = fgets($handle)) !== false) { echo $line;}fclose($handle);写入文件
// 写入全部file_put_contents('file.txt', 'content');// 追加file_put_contents('file.txt', 'append', FILE_APPEND);// 逐行写入$handle = fopen('file.txt', 'w');fwrite($handle, "Hello\n");fclose($handle);文件系统
file_exists($path);is_file($path);is_dir($path);filesize($path);filemtime($path);unlink($file); // 删除文件mkdir($dir);rmdir($dir);rename($old, $new);JSON 操作
// 序列化$json = json_encode($array);$json = json_encode($data, JSON_PRETTY_PRINT);// 反序列化$array = json_decode($json, true);$obj = json_decode($json);超全局变量
HTTP 请求
$_GET['param'];$_POST['field'];$_REQUEST['data'];$_SERVER['REQUEST_METHOD'];$_SERVER['HTTP_HOST'];$_SERVER['REQUEST_URI'];$_FILES['upload'];$_COOKIE['session'];$_SESSION['user'];$_ENV['APP_KEY'];处理表单
if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name'] ?? 'default'; $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); if ($email === false) { echo "Invalid email"; }}数据库
PDO
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');// 查询$stmt = $pdo->query('SELECT * FROM users');$users = $stmt->fetchAll(PDO::FETCH_ASSOC);// 预处理语句$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');$stmt->execute([$id]);$user = $stmt->fetch();// 插入$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');$stmt->execute([$name, $email]);MySQLi
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');// 查询$result = $mysqli->query('SELECT * FROM users');while ($row = $result->fetch_assoc()) { echo $row['name'];}// 预处理$stmt = $mysqli->prepare('SELECT * FROM users WHERE id = ?');$stmt->bind_param('i', $id);$stmt->execute();$result = $stmt->get_result();常用函数
日期时间
date('Y-m-d H:i:s');time();strtotime('2024-01-01');strtotime('+1 day');$dt = new DateTime();$formatted = $dt->format('Y-m-d');$dt->modify('+1 day');数学函数
abs($x);ceil($x);floor($x);round($x);max($a, $b, $c);min($a, $b, $c);pow($base, $exp);sqrt($x);rand($min, $max);类型检查
is_int($var);is_string($var);is_array($var);is_object($var);is_null($var);is_numeric($var);is_callable($var);gettype($var);get_class($obj);输出控制
echo "Hello";print "World";var_dump($var);print_r($array);var_export($data);header('Content-Type: application/json');header('Location: /page.php');http_response_code(404);最佳实践
代码风格 (PSR-12)
// 使用类型声明function add(int $a, int $b): int { return $a + $b;}// 使用 null 合并$name = $_GET['name'] ?? 'default';// 使用严格类型 (PHP 7+)declare(strict_types=1);安全性
// 防止 SQL 注入$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');$stmt->execute([$id]);// 防止 XSSecho htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');// 密码哈希$hash = password_hash($password, PASSWORD_DEFAULT);password_verify($password, $hash);// CSRF 令牌$token = bin2hex(random_bytes(32));常见陷阱
// == vs ===0 == '0' // true0 === '0' // false// 数组键$arr[0] !== $arr['0'] // false (相同)// 字符串连接性能// 用 . 而非 += 拼接大量字符串$parts = [];$parts[] = $str1;$parts[] = $str2;$result = implode('', $parts);工具链
Composer
# 安装依赖composer installcomposer require package# 自动加载composer dump-autoload# 更新composer update测试框架
# PHPUnit./vendor/bin/phpunit# Pest./vendor/bin/pest代码质量
# PHP-CS-Fixer (格式化)php-cs-fixer fix# PHPStan (静态分析)phpstan analyse# Psalm (静态分析)psalm框架
# Laravelcomposer create-project laravel/laravel myappphp artisan serve# Symfonycomposer create-project symfony/skeleton myappsymfony serve