php 8.6可用splfixedarray保存固定条数的最近日志:写指针循环前进,满容量后覆盖最旧记录,读取时从最旧有效位置开始重排。固定的是槽位数量,消息长度和php对象开销仍需另外限制,不能据此承诺固定字节内存。

PHP手册中的PHP: SplFixedArray - Manual
实现有界环形缓存
<?php final class RecentLog {
private SplFixedArray $items;
private int $next=0;
private int $used=0;
public function __construct(private int $capacity) {
if ($capacity<1 || $capacity>10000) {
throw new InvalidArgumentException('容量不符');
}
$this->items=new SplFixedArray($capacity);
}
public function push(string $message):void {
if (strlen($message)>2048) throw new LengthException('单条过长');
$this->items[$this->next]=$message;
$this->next=($this->next+1)%$this->capacity;
$this->used=min($this->used+1,$this->capacity);
}
public function all():array {
$out=[]; $start=($this->next-$this->used+$this->capacity)%$this->capacity;
for ($i=0;$iused;$i++) {
$out[]=$this->items[($start+$i)%$this->capacity];
}
return $out;
}
}
$log=new RecentLog(3);
foreach (['A','B','C','D'] as $message) $log->push($message);
echo json_encode($log->all(),JSON_THROW_ON_ERROR);

PHP手册中的PHP: SplFixedArray::offsetSet - Manual
检查覆盖顺序
示例最终应按B、C、D顺序返回。未满时只返回已写入记录,不把初始null槽位当作日志;SplFixedArray越界访问会失败,因此索引始终通过容量取模。
仅用于当前进程的临时诊断
缓存随进程结束而消失,不是审计日志或跨进程共享存储。敏感字段仍应在写入前脱敏;需要长期保存时另用受控日志出口,而不是无限扩大环形容量。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










