以下是PHP常用语法的系统化汇总,结合最新特性与最佳实践整理:
一、基础语法结构
<?php
// 标准脚本标记(推荐)
echo "Hello World!"; // 输出语句
?>- 短标记:<?= "Hello";?>(需short_open_tag开启)
- 混合HTML:可在同一文件内多次使用PHP标签
二、变量与常量
// 变量(动态类型)
$name = "John"; // 字符串
$age = 30; // 整型
$is_active = true; // 布尔型
$prices = [19.99,29.99]; // 浮点型数组
// 常量
define("PI", 3.14159); // 传统方式
const MAX_LOGIN = 5; // PHP 5.3+ 推荐[8](@ref)- 作用域:局部/全局/静态/参数作用域,全局变量需global关键字访问
- 类型转换:(int)$var强制转换,settype($var,'string')改变原值
三、数据类型详解
类型 | 示例 | 特性 |
字符串 | $s1='It\'s OK' | 单引号不解析变量,双引号解析 |
数组 | [1,2](@ref) | 支持索引/关联/多维数组 |
对象 | new stdClass() | 需先定义类 |
特殊类型 | null/resource | null表示无值,resource存外部资源 |
四、运算符优先级(高→低)
$a = 3 * 3 % 5; // (3 * 3)%5=4[14](@ref)$b = $a ?? 0 ?? 1; // 空合并运算符(PHP7+)[3](@ref)$c = $x ?? $y ?? $z; // 依次判断非空值[15](@ref)```
| 优先级 | 运算符 | 说明 |
|--------|---------------------|--------------------------|
| 1 | `clone`/`new` | 对象创建[14](@ref)|
| 2 | `**` | 幂运算(PHP5.6+)[2](@ref)|
| 3 | `++`/`--` | 后置优先于前置[15](@ref)|
| 4 | `!` | 逻辑非[14](@ref)|
### 五、控制结构
```php
// 条件判断
if ($age >= 18) {
echo "成年人";
} elseif ($age >= 65) {
echo "老年人";
} else {
echo "未成年人";
}
// 循环结构
for ($i=0; $i<5; $i++) {
echo $i;
}
while ($count < 10) {
$count++;
}
do {
// 至少执行一次
} while ($condition);- 跳转控制:break/continue/goto(慎用)
六、函数与闭包
// 命名函数
function calculateArea($w, $h) {
return $w * $h;
}
// 匿名函数
$formatter = function($num) {
return number_format($num);
};
echo $formatter(1234.56); // 1,234.56
// 类型声明(PHP7+)
function sum(int ...$nums): int {
return array_sum($nums);
}- 可变参数:function func(...$args)
- 引用传参:function inc(&$n) { $n++; }
七、数组操作
// 索引数组
$fruits = ["Apple", "Banana"];
array_push($fruits, "Orange"); // 添加元素
// 关联数组
$user = [
"name" => "Bob",
"email" => "bob@example.com"
];
foreach ($user as $key => $val) {
echo "$key: $val";
}
// 多维数组
$matrix = [[1,2](@ref)];
array_walk($matrix, function($row) {
sort($row);
});- 常用函数:array_map()/array_filter()/array_reduce()
八、面向对象编程
class User {
public string $name;
protected int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public static function createAdmin() {
return new self("Admin", 30);
}
}
interface Authenticatable {
public function validate(): bool;
}
class Admin extends User implements Authenticatable {
public function validate() {
return $this->age >= 18;
}
}- 特性:可见性控制、继承、接口、Trait代码复用
九、文件与数据库
// 文件操作
$content = file_get_contents("data.txt");
file_put_contents("log.txt", "Error: ".date("Y-m-d H:i:s"));
// MySQLi连接
$conn = new mysqli("localhost", "user", "pass", "db");
$stmt = $conn->prepare("SELECT * FROM users WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();- 安全建议:使用预处理语句防SQL注入
十、错误处理
// 异常捕获
try {
if ($count < 0) {
throw new Exception("计数不能为负");
}
} catch (Exception $e) {
error_log($e->getMessage());
} finally {
// 清理资源
}
// 自定义错误处理
set_error_handler(function($errno, $errstr) {
if ($errno === E_USER_NOTICE) {
return; // 忽略特定错误
}
throw new ErrorException($errstr, 0, $errno);
});- 日志管理:建议配合Monolog等专业库
扩展特性
- 命名空间:namespace App\Controllers; 避免类名冲突
- 自动加载:PSR-4标准配合Composer实现类自动加载
- CLI脚本:php -r 'echo "Hello CLI";' 执行命令行任务
建议结合官方PHP手册和实际项目实践,重点关注PHP 7.4+的新特性(如箭头函数、JIT编译)。对于Web开发,还需掌握会话管理($_SESSION)、表单处理($_POST)、安全过滤(htmlspecialchars())等核心技能。