自动加载
Composer 最实用的功能之一:PSR-4 自动加载。按命名空间规则放好文件,不用手写 require 就能用类,代码干净整洁。
PSR-4 规则
composer.json 里 "App\\": "src/" 表示 App\ 开头的类都在 src/ 目录找,子命名空间对应子目录,类名对应文件名。
使用
页面入口 require "vendor/autoload.php" 一次,之后所有类自动加载。新增类后跑 composer dump-autoload。
代码示例
// composer.json
// "autoload": { "psr-4": { "App\\": "src/" } }
// src/Service/UserService.php
<?php
namespace App\Service;
class UserService {
public function getName(): string {
return "张三";
}
}
?>
// index.php 使用(无需手动 require)
<?php
require "vendor/autoload.php";
$user = new \App\Service\UserService();
echo $user->getName();
?>
📚 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) | 写入文件 |