缘起
今天,和我一起做项目的朋友跟我提了一个问题,他让我尽量使用 include
,少使用 require
,这使我感到十分奇怪。
询问一下,他给出的答案竟然是 include
好控制,而 require
不好控制,并且提出了一个让我感到奇怪的观点——require
在计算为假的语句中也会执行。
这,我在 PHP 手册中从来没看到过,也从来没听说过。
分析
PHP 手册中说:
如果最后仍未找到文件则
include
结构会发出一条警告;这一点和require
不同,后者会发出一个致命错误。
require
和include
几乎完全一样,除了处理失败的方式不同之外。require
在出错时产生 E_COMPILE_ERROR 级别的错误。换句话说将导致脚本中止而include
只产生警告(E_WARNING),脚本会继续运行。
实践
对于这个问题,我决定试试看,毕竟实践出真知。闲来无聊,试试看不就知道了。
测试环境:PHP 5.3.28
代码:
file.php:
<?php echo 'Is Show?' ?>
require.php
<?php echo 'Hello!' if (false) { require 'file.php'; } ?>
结果,得到了以下输出:
Hello!
现在有答案了吧?
更多内容见:
我在知乎的提问:PHP require 在计算为假的语句中也会执行?
whoah this blog is excellent i love reading your posts. Keep up the good work! You know, a lot of people are looking around for this info, you could help them greatly. Lisha Gib Harshman
Good day! This post could not be written any better! Reading this post reminds me of my previous room mate! He always kept chatting about this. I will forward this write-up to him. Pretty sure he will have a good read. Thank you for sharing!| Minni Ruddy Sessler
I watched the vendors software demo video on the JV page and to me the low quality of the demo video he produced would not entice me to buy! Callie Adan Fontana
Way cool! Some very valid points! I appreciate you writing this post and also the rest of the website is also really good. Sal Hartley Hazlett
After I initially commented I seem to have clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get four emails with the exact same comment. Perhaps there is a means you are able to remove me from that service? Thanks a lot. Colly Ruperto Rozalie
Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate? Nita Mord Gupta
I love this book, and your Sunbolt series too! Congratulations on the beautiful cover and your upcoming trad release of Thorn! Angil Skyler Andie
We have no information at the moment on of caused death . This post will be updated as soon as we have that information. Catherin Nico Berry
Just fast in your own, and see how it goes? As Dr. Fung remarks: Its doing nothing. Jessalyn Domenic Lilllie
There is a lot of misunderstanding about these issues today. Your material helps explain things. Meredithe Kevon Elyssa
Por su labor informativa, por supuesto mi voto va para Radio El Respeto de Pablo Fuente. Vikky Andy Hoban
It is the best time to make some plans for the long run and it is time to be happy. Anderea Johannes Herrle
Great amazing things here. I am very satisfied to see your article. Thanks so much and i am looking ahead to contact you. Will you please drop me a e-mail? Cinderella Nickey Zoeller
You need to participate in a contest for among the best blogs on the web. I will suggest this web site! May Ase Josy