当前位置:网站首页>PHP require/include 区别
PHP require/include 区别
2022-06-30 20:05:00 【烟草的香味.】
前言
在PHP中, 载入文件可以选择使用require, 也可以使用include, 那么那他们有什么区别呢? 看了网上的一些文章, 说他们使用场景不同, require一般在文件开头引入文件, include一般在函数中动态引入文件.
但是我觉得并不是这么简单, require是作为语言结构(关键字)出现的, 关键字这玩意对于语言设计者来说一般都是越少越好, 关键字少了语言才简单嘛. 于是我决定深入到源码级别来康康他们的区别.
探究
通过查看, require/require_once/include/include_once这几个方法翻译后是同一个c函数ZEND_INCLUDE_OR_EVAL_SPEC_CONST_HANDLER.
如何拿到这个c函数可看这篇文章: https://hujingnb.com/archives/836
查看方法:

include/require
include/require方法的处理方式相同. 我们先看他们的区别, 再去看_once方法的区别.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2bjPcQLE-1656157366388)(https://oss-blog.cdn.hujingnb.com/img/202206251901506.png)]
通过查找, include与require的唯一区别, 就是当文件不存在的时候处理方式不同.

再次查找, 对于二者的处理方式如图所示(这个报错文案确实是文件不存在时候的文案). 对于调用的两个方法作用如下:
php_error_docref: 抛出php级别错误. 因为这里抛出的warning级别, 故不会令脚本停止.zend_throw_error: 抛出编译期异常, 会终止脚本执行.
因此, 通过比较看到, require和include的唯一区别, 就是当文件不存在的时候, require会终止脚本执行, include仅抛出warning错误.
这里在zend_throw_error方法中看到了下面注释, 其中提到当前无法将编译期错误转换为exception. 可能未来会支持??

include_once/require_once
通过查看源码, include_once/require_once的区别, 与include/require一样, 都是在对待异常的处理上不同, 其他完全一样

结论
因此, include和require的唯一区别, 就是当文件不存在的时候, require会终止进程, 而include不会.
啊, 这, 整两个如此相似的关键字真的好么, 如果说, 将require去掉, 然后通过include返回值来判断文件是否存在, 由调用者来判断是否要终止进程, 这样是否会更合理一些呢? 亦或者PHP的设计师们是出于其他方面的考虑?
边栏推荐
- Heartbeat uses NFS to make MySQL highly available based on CRM
- [iccv 2019] characteristics precise supervision of feature super resolution for small object detection
- SecureCRTPortable的安装和使用(图文详解)
- 操作系统面试题汇总(不定期更新)
- maya房子建模
- HeartBeat基于CRM使用NFS对MySQL高可用
- Implementation principle of PostgreSQL heap table storage engine
- Halcon知识:盘点一下计量对象【1】
- 为什么一定要从DevOps走向BizDevOps?
- Great God detailed open source Buff gain Introduction 丨 Live
猜你喜欢
随机推荐
Installation and use of securecrtportable
Exness: liquidity series - liquidity cleaning and reversal, decision interval
Is it safe to open an account in Guangzhou stock exchange by mobile phone?
Network planning | [five transport layers and six application layers] knowledge points and examples
股票开户优惠链接,我如何才能得到?另外,手机开户安全么?
大神详解开源 BUFF 增益攻略丨直播
Mistakes the project manager should not make
VB的基本语法
Openfire solves the problem of Chinese garbled code after using MySQL database
Pytorch implements the calculation of flops and params
Great God detailed open source Buff gain Introduction 丨 Live
NLP技能树学习路线-(一)路线总览
如何快速通过PMP考试?
Heartbeat 与DRBD 配置过程
PM reports work like this, and the boss is willing to give you a raise
The Commission is so high that everyone can participate in the new programmer's partner plan
杰理之关于长按开机检测抬起问题【篇】
Go 语言标识符、包名规范
Cv+deep learning network architecture pytoch recurrence series basenets (backbones) (I)
静态类使用@Resource注解注入
![[try to hack] windows system account security](/img/2b/e6e999313e3ae4e1cbf4bfa02daef0.png)








