欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP中include和require的區(qū)別實(shí)例分析

 更新時(shí)間:2017年05月07日 10:40:56   作者:編程老頭  
網(wǎng)上太多關(guān)于PHP中include與require區(qū)別。然而事實(shí)真的如此嗎,今天我們就通過一個(gè)具體的實(shí)例來簡(jiǎn)單分析驗(yàn)證下

先編輯command.php文件

echo 'hello'.PHP_EOL;

然后編輯console.php文件

for($i=1;$i<=3;++$i){
	require 'command1.php';
}

原本想要包含并執(zhí)行這個(gè)echo,沒想到寫錯(cuò)了文件名,如果是require,會(huì)報(bào)出這樣的錯(cuò)誤:

Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4

Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4
PHP Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4

如果把require改為include

for($i=1;$i<=3;++$i){
	include 'command1.php';
}

會(huì)報(bào)出這樣的錯(cuò)誤:

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

如果使用require_once或者include_once,只要包含路徑正確,那么循環(huán)只執(zhí)行一次。

總結(jié):

使用require,如果文件沒有包含成功,就會(huì)報(bào)出一個(gè)fatal error,整個(gè)程序就中止了。

使用include,如果文件沒有包含成功,就會(huì)報(bào)出一個(gè)普通的warning,之后的代碼仍會(huì)執(zhí)行。

如果你的Web程序使用了MVC這種對(duì)文件包含強(qiáng)依賴的設(shè)計(jì)方法,請(qǐng)使用require_once。

相關(guān)文章

最新評(píng)論