覆盖PHP 7/8全版本核心考点|真实企业真题解析|高频追问场景还原|性能调优实战指南
PHP采用弱类型设计,但PHP 7+已引入严格的类型声明机制。理解类型系统是避免运行时错误的关键:
示例:严格模式下的类型约束
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, "3"); // TypeError: Argument 2 passed to add() must be of type int, string given
?>
注意:PHP 8引入union types(联合类型)与named arguments(命名参数):
<?php
function process(string|int $value): void { ... }
process(value: 123); // 命名参数提升可读性
?>
PHP使用refcount与is_ref实现zval容器管理变量:
典型面试题:以下代码输出什么?
<?php
$a = ['x'];
$b = &$a;
$a[] = 'y';
print_r($b);
?>
答案:Array ( [0] => x [1] => y ),因$b是$a的引用,修改$a直接影响$b
引入Zend Engine 1.0,支持模块化扩展(mod_php/Apache)
Zend Engine 2.0发布,完善OOP支持(final/abstract/interface)
Zend Engine 3.0重构,性能提升2倍;引入标量类型声明、返回类型
支持属性类型声明、预加载(Preloading)
JIT编译器、联合类型、构造器属性提升、match表达式、nullsafe操作符
示例:违反SRP的重构
<?php
// ❌ 违反单一职责:User类既管理数据又处理输出
class User {
public $name;
public function save() { ... }
public function renderHtml() { ... } // 业务逻辑混入
}
// ✅ 重构后:分离职责
class User {
public $name;
public function save() { ... }
}
class UserView {
public static function render(User $user): string { ... }
}
?>
工厂模式示例:
<?php
interface DatabaseDriver { public function connect(); }
class MysqliDriver implements DatabaseDriver {
public function connect() { }
}
class PdoDriver implements DatabaseDriver {
public function connect() { }
}
class DatabaseFactory {
public static function create(string $type): DatabaseDriver {
return match($type) {
'mysqli' => new MysqliDriver(),
'pdo' => new PdoDriver(),
default => throw new InvalidArgumentException("Unknown driver"),
};
}
}
?>
属性注解对比:
<?php
// 传统注解方式(需第三方库)
public function getUserAction(User $user) { ... }
// PHP 8原生Attributes
#[Route("/users", methods: ['GET'])]
#[ParamConverter('user', class: User::class)]
public function getUserAction(User $user) { ... }
?>
/user/{id} → Controller::showAction)简化版路由实现:
<?php
// Router.php
class Router {
private $routes = [];
public function add(string $path, callable $callback): void {
$this->routes[$path] = $callback;
}
public function dispatch(string $uri): void {
foreach ($this->routes as $pattern => $callback) {
if ($this->match($pattern, $uri)) {
$callback();
return;
}
}
http_response_code(404);
echo "Not Found";
}
private function match(string $pattern, string $uri): bool {
// 简化版匹配逻辑
return preg_match('#^'.str_replace(['{[a-z]+}'], ['[a-z]+'], $pattern).'#', $uri);
}
}
?>
| 框架 | 学习曲线 | 性能 | 生态 | 适用场景 |
|---|---|---|---|---|
| Laravel | 低 | 中 | 极高 | 中大型Web应用 |
| Symfony | 中 | 高 | 高 | 企业级系统 |
| ThinkPHP | 低 | 高 | 国内社区 | 国内项目 |
| Yii | 中 | 极高 | 中 | 高并发API |
| Swoole | 高 | 极高 | 新兴 | 协程/常驻内存 |
注意:Swoole通过协程实现异步非阻塞,但需注意coroutine上下文隔离问题
XSS(跨站脚本)分三类:
?q=<script>)防御策略:
htmlspecialchars($str, ENT_QUOTES, 'UTF-8')Content-Security-Policy: script-src 'self'错误示例:
<?php
echo "搜索结果:".$_GET['q']."
"; // 直接输出未转义
?>
正确做法:
<?php
echo "搜索结果:".htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8')."
";
?>
常见攻击方式:
WHERE id=1 OR 1=1UNION SELECT * FROM users'; DROP TABLE users; --正确防护方案:
PDO预处理示例:
<?php
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND status = :status");
$stmt->execute(['email' => $email, 'status' => 'active']);
$user = $stmt->fetch();
?>
注意:mysqli_real_escape_string不是万能方案!预处理才是唯一可靠方案
$_SESSION['csrf_token'])Set-Cookie: session=abc; SameSite=StrictToken生成与验证:
<?php
// 生成Token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// 表单中
<input type="hidden" name="csrf_token" value="">
// 验证
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token validation failed');
}
?>
isset代替array_key_existsstr_replace而非preg_replaceSELECT *opcache.validate_timestamps=0(生产环境)| 参数 | 默认值 | 推荐值 | 说明 |
|---|---|---|---|
| pm | dynamic | static | 静态进程池减少动态分配开销 |
| pm.max_children | 5 | 根据内存计算 | 内存GB数×100 ÷ 单进程内存 |
| pm.max_requests | 500 | 1000 | 防止内存泄漏 |
| request_terminate_timeout | 0 | 30s | 防止脚本无限执行 |
计算示例:4GB内存服务器 → 4×100=400,单进程约40MB → 400÷40=10个进程
Redis缓存最佳实践:
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 尝试从缓存获取
$cacheKey = 'user:123:profile';
$user = $redis->get($cacheKey);
if (!$user) {
$user = $db->query("SELECT * FROM users WHERE id=123");
$redis->setex($cacheKey, 3600, json_encode($user)); // 缓存1小时
}
?>
错误索引设计导致全表扫描:
SELECT * FROM orders WHERE DATE(created_at) = '2023-01-01';
正确写法(避免函数包裹字段):
SELECT * FROM orders
WHERE created_at >= '2023-01-01 00:00:00'
AND created_at < '2023-01-02 00:00:00';
联合索引顺序原则:高频查询字段在前,等值查询在前,范围查询在后
开启慢查询日志:
SET GLOBAL slow_query_log = ON;
SET GLOBAL long_query_time = 1; -- 执行超过1秒的SQL记录
使用EXPLAIN分析执行计划:
| 字段 | 含义 | 优化方向 |
|---|---|---|
| type | 连接类型 | 避免ALL(全表扫描) |
| key | 使用索引 | 检查是否走索引 |
| rows | 扫描行数 | 越少越好 |
| Extra | 额外信息 | 警惕Using filesort/Using temporary |
分表策略示例:
user_00: id % 100 = 0
user_01: id % 100 = 1
...
user_99: id % 100 = 99
int|float)示例:Readonly类
<?php
readonly class User {
public function __construct(
public string $name,
public int $age
) {}
}
$user = new User("张三", 28);
$user->name = "李四"; // Fatal error: Cannot modify readonly property
?>
问题:Laravel中app()->make('App\Services\PaymentService')做了什么?
答案:
DECRRedis Lua脚本示例:
if redis.call('get', KEYS[1]) > 0 then
redis.call('decr', KEYS[1])
return redis.call('lpush', KEYS[2], ARGV[1])
else
return 0
end
典型场景:如何保证线上代码质量?
答:采用四层防护体系