[PHP] include_once 和 require_once

include_once 和 require_once都是PHP的函式,主要是要包含其它的檔案進來,而且萬一該檔案被包含過了,則不會重新再包含一次。

而基於PHP不可能開發同一個函式的情況下,去試了一下他的不同之處,在於include_once萬一遇到錯誤,則會持續執行,但require_once則會停止執行,並產生Fatal Errors。

以程式碼說明如下:

檔名:test.php

<?php
  require_once("a.php");
  require_once("c.php");
  echo dirname(__FILE__)." in test.php\n";
?>

 

檔名:a.php

<?php
  echo dirname(__FILE__)." in a.php"."</br>";
  require_once("b.php");
?>

 

檔名:b.php

<?php
  echo dirname(__FILE__)." in b.php"."</br>";
?>

 

使用「require_once」會出現下列結果:

C:\AppServ\www\PTS in a test.php
C:\AppServ\www\PTS in b test.php

Warning: require_once(c.php) [function.require-once]: failed to open stream: No such file or directory in C:\AppServ\www\PTS\test.php on line 3

Fatal error: require_once() [function.require]: Failed opening required 'c.php' (include_path='.;C:\php5\pear') in C:\AppServ\www\PTS\test.php on line 3

 

但若是改成include_once,則會變成

C:\AppServ\www\PTS in a test.php
C:\AppServ\www\PTS in b test.php

Warning: require_once(c.php) [function.require-once]: failed to open stream: No such file or directory in C:\AppServ\www\PTS\test.php on line 3

Warning: include_once() [function.include]: Failed opening 'c.php' for inclusion (include_path='.;C:\php5\pear') in C:\AppServ\www\PTS\test.php on line 3
C:\AppServ\www\PTS in test.php

 

About 張海芋

城市裡的小小迷僮工程師,喜歡用鍵盤記錄個人生活的點滴,身邊的人事物都我的靈感,用心踏出每個腳步,用文字灌溉《海芋小站》,用專業解決問題。

發表迴響