doudi2431 2012-04-05 19:17
浏览 120
已采纳

循环中的PHP include_once或require_once

Quick question about include/requre_once . I have some code that is common to a few pages that I feel would be better to be in a file to call from each page rather than code repetition.

I call the include_once in a while loop and what I noticed is that I have to use include('file.php') or it will literally load it (and display it) only once . I guess what I assumed ( incorrectly) is that it will load it on the first loop and retain the code in a cache to avoid having to access the disk each iteration of the loop.

I looked around for a "load_once_and_cache" type of command but did not find anything.

Does anyone have any suggestions for this or is putting the code in each page the only option.

Thanks again!

  • 写回答

2条回答 默认 最新

  • dprxj1995 2012-04-05 19:19
    关注

    This is a pretty inefficient method of getting content into a loop. PHP would need to read the file from disk on each include() call. You're much better off creating a function (which may be in the included file). Include the file once, which defines the function, then call the function in your loop.

    It isn't always good practice to rely on the output of an included file, except perhaps when coding a view (even then I'd think twice before doing it). Requiring a file to be included inside a loop creates a strange mix of flow control and file inclusion that can be difficult to debug and maintain.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害