函数
PHP 函数用 function 定义。支持默认参数、可变参数、类型声明、返回值类型声明等现代特性。
要点
- 默认参数:
function f($a, $b = 10),默认值要放后面; - 可变参数:
...$args收集为数组; - 类型声明:
function f(int $a): string; - 严格模式:文件首行
declare(strict_types=1);; - 匿名函数 / 闭包:
function($x) use ($y) {...}; - 箭头函数(PHP7.4+):
fn($x) => $x * 2。
代码示例
<?php
declare(strict_types=1);
// 基本函数 + 默认参数
function greet($name, $greeting = "你好") {
return "$greeting,$name";
}
echo greet("小王"); // 你好,小王
echo "<br>" . greet("小李", "欢迎");
// 类型声明
function add(int $a, int $b): int {
return $a + $b;
}
echo "<br>" . add(3, 5); // 8
// 可变参数
function total(...$nums) {
return array_sum($nums);
}
echo "<br>" . total(1, 2, 3, 4); // 10
// 匿名函数与 use
$base = 100;
$calc = function($x) use ($base) {
return $x + $base;
};
echo "<br>" . $calc(50); // 150
// 箭头函数
$double = fn($x) => $x * 2;
echo "<br>" . $double(21); // 42
?>
📚 PHP 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
<?php ... ?> | PHP 代码块标记 |
echo "hello"; | 输出字符串 |
$name = "张三"; | 变量(以 $ 开头,无需声明类型) |
if ($x > 0) { } else { } | 条件判断 |
foreach ($arr as $k => $v) { } | 遍历数组(最常用) |
for ($i = 0; $i < 10; $i++) { } | 计数循环 |
function fn($a) { return $a; } | 定义函数 |
array("a" => 1) | 关联数组(PHP 的"字典") |
count($arr) | 数组长度 |
isset($x) / empty($x) | 变量是否存在 / 是否为空 |
$_GET["key"] / $_POST["key"] | 获取表单 / 查询参数 |
$_SESSION["user"] | 会话数据读写(需 session_start()) |
$_COOKIE["key"] | 读取 Cookie |
header("Location: /index.php"); | 页面跳转 |
mysqli_connect($host, $user, $pass, $db) | 连接 MySQL(旧接口,新项目用 PDO) |
new PDO($dsn, $user, $pass) | 连接 MySQL(推荐,防 SQL 注入) |
$stmt->prepare($sql) | 预处理语句(防 SQL 注入) |
htmlspecialchars($str) | HTML 转义(防 XSS) |
strlen($s) / mb_strlen($s) | 字符串长度 |
explode(",", $s) / implode(",", $arr) | 字符串拆分 / 拼接 |
json_encode($arr) / json_decode($s) | 数组与 JSON 互转 |
include / require | 引入文件(require 报错即停) |
date("Y-m-d H:i:s") | 当前时间格式化 |
$_FILES["file"] | 文件上传数据 |
file_put_contents($path, $data) | 写入文件 |