当前位置:网站首页>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的设计师们是出于其他方面的考虑?
边栏推荐
- Why should offline stores do new retail?
- Big God explains open source buff gain strategy live broadcast
- 神经网络入门(上)
- Introduction to neural network (Part 1)
- 杰理之触摸按键识别流程【篇】
- CADD课程学习(2)-- 靶点晶体结构信息
- STL的基本组成部分
- Go 语言标识符、包名规范
- PM reports work like this, and the boss is willing to give you a raise
- Primary school, session 3 - afternoon: Web_ sessionlfi
猜你喜欢

Why must we move from Devops to bizdevops?

建立自己的网站(20)

NLP 论文领读|文本生成模型退化怎么办?SimCTG 告诉你答案

What is the difference between tolocal8bit and toutf8() in QT

maya房子建模

Enterprise middle office planning and it architecture microservice transformation
![Jerry's touch key recognition process [chapter]](/img/ec/25d2d6fd26571e4fb642129a4eee1b.png)
Jerry's touch key recognition process [chapter]

Solve the problems of Devops landing in complex environment with various tools with full stack and full function solutions

好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与

Primary school, session 3 - afternoon: Web_ sessionlfi
随机推荐
Heartbeat 与DRBD 配置过程
All the important spark summit features were released here last night (with ultra clear video attached)
黑苹果 服务器系统安装教程,黑苹果安装教程,详细教您黑苹果怎么安装[通俗易懂]
操作系统面试题汇总(不定期更新)
微信小程序开发实战 云音乐
Openfire在使用MySQL数据库后的中文乱码问题解决
Basic syntax of VB
Why should offline stores do new retail?
杰理之检测灵敏度级别确定【篇】
Build your own website (20)
Summary of PHP file upload (garbled code, move failure, permission, display picture)
CADD课程学习(2)-- 靶点晶体结构信息
Client请求外部接口标准处理方式
杰理之关于长按开机检测抬起问题【篇】
大神详解开源 BUFF 增益攻略丨直播
Heartbeat and DRBD configuration process
杰理之触摸按键识别流程【篇】
【Try to Hack】Windows系统账户安全
Jerry's question about long press boot detection [chapter]
DEX file parsing - Method_ IDS resolution