You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:如何实现延迟求值的静态变量以优化函数性能

解决PHP函数中延迟初始化静态变量的问题

你可以通过在函数内部声明静态变量,并结合条件判断实现延迟求值,确保scandir和array_map仅在第一次调用时执行。具体修改如下:

function attachImagesToProduct(Product $csProduct) {
    static $files = null;
    
    if ($files === null) {
        $searchPath = realpath(__DIR__ . "/../images");
        $files = scandir($searchPath);
        $files = array_map(function ($file) use ($searchPath) {
            return $searchPath . "/" . $file;
        }, $files);
    }
    
    // 后续业务逻辑,直接复用$files变量
}

原理说明

  • static $files = null 声明静态变量,该变量的生命周期会跨越函数的多次调用,不会在函数执行完毕后销毁。
  • 第一次调用函数时,$files为null,进入条件分支执行文件扫描和路径拼接操作,完成后将结果赋值给$files。
  • 后续调用函数时,$files已经保存了之前的计算结果,直接跳过耗时的文件操作,复用已有数据。

可选扩展(按需使用)

如果后续需要刷新文件列表(比如目录内文件有更新),可以增加一个可选参数控制是否重新加载:

function attachImagesToProduct(Product $csProduct, bool $refreshFiles = false) {
    static $files = null;
    
    if ($files === null || $refreshFiles) {
        $searchPath = realpath(__DIR__ . "/../images");
        $files = scandir($searchPath);
        $files = array_map(function ($file) use ($searchPath) {
            return $searchPath . "/" . $file;
        }, $files);
    }
    
    // 后续业务逻辑
}

内容的提问来源于stack exchange,提问作者user26333271

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:11:02