PHP require 在计算为假的语句中也会执行?大错特错

文章目录[隐藏]

缘起

今天,和我一起做项目的朋友跟我提了一个问题,他让我尽量使用 include,少使用 require,这使我感到十分奇怪。

询问一下,他给出的答案竟然是 include 好控制,而 require 不好控制,并且提出了一个让我感到奇怪的观点——require 在计算为假的语句中也会执行。
这,我在 PHP 手册中从来没看到过,也从来没听说过。

分析

PHP 手册中说:

如果最后仍未找到文件则 include 结构会发出一条警告;这一点和 require 不同,后者会发出一个致命错误。

requireinclude 几乎完全一样,除了处理失败的方式不同之外。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 在计算为假的语句中也会执行?

此文章是由nikbobo发表在PHP分类目录的。将固定链接加入收藏夹。

关于 nikbobo

Nikbobo,本名刘永强,记忆空间站长,男,1998 年出生于广东茂名,至今(2020 年)21 岁,目前(2020 年)就读于广州大学华软软件学院,常以“nikbobo”这个网名混迹互联网。如无特殊注明,Nikbobo 在本站发表的文章,遵循 知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议。详情请参阅关于页面的作者介绍。

PHP require 在计算为假的语句中也会执行?大错特错》上有14个想法

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. I love this book, and your Sunbolt series too! Congratulations on the beautiful cover and your upcoming trad release of Thorn! Angil Skyler Andie

  8. 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

  9. 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

发表评论

邮箱地址不会被公开。 必填项已用*标注