包括外部php文件

我正在使用一些PHP程式碼,如資料庫連線,這對所有頁面都很常見,所以我建立了一個包含php程式碼的php文件,然後我將這個文件包含在我的HTML程式碼中,

所以我想知道更好的方法來包含php文件,更好的替代include函式.

我的示例程式碼在這裡

<?php
    include "check_timeout.php";
    include "connect_to_db.php";
?>
<html>
<head>
    <title>Example</title>
</head>
<body>
<?php
    mysql_close($con);
?>
</body>
</html>

先感謝您.

您有4個選項可供選擇.

包括’yourfile.php’;

include_once’yourfile.php’;

要求’yourfile.php’;

require_once’yourfile.php’;

當然你也可以用“代替”.

他們都會做同樣的事情,除了微小的差異.

如果yourfile.php不存在,則包含的將忽略該事實,並且您的php頁面將繼續 – 沒有任何致命錯誤.

另一方面,需要的會產生致命的錯誤.

如果你知道那個文件在那裡,你選擇哪一個沒什麼區別.

至於帶有_once字尾的選項,嗯,與它們的非_once後固定對應物相比,它們往往更慢.因為當你使用include_once或require_once時,PHP會做一些額外的工作來確保那些文件真正包含在ONCE中 – 保護你免受可能的雙重包含情況,如果你不小心編碼和許多文件使用許多包含你可能會遇到兩次包含相同文件的情況.好吧,_once選項會阻止它.而且檢查會帶來一些處理成本.

我還注意到你已經使用了“而不是”用於文件分隔符.沒有理由選擇“over”,除非你在文件中引用變數名稱,例如

$thefile =’yourfile.php;

包括“$thefile”;

那麼從這4箇中選出哪些?

這一切都取決於,如果你認為你確實需要強制_once問題,那麼你選擇include_once或require_once,如果你認為不需要,那麼你選擇include或require.至於include vs require,如果你的文件由於某種原因無法訪問,那麼你是否希望你的PHP指令碼死掉或繼續前進.

如果您對某些速度測試感到好奇,這裡有一個連結供您檢視.

http://php.net/manual/en/function.require-once.php

我也在主題上找到了這個.

Understanding the difference between require and include According to  the PHP manual, require and include “are identical in every way except  how they handle failure.” However, further reading of the manual  suggests another very subtle difference that impacts performance. When  you use the require keyword, the named file is read in, parsed, and  compiled when the file using the require keyword is compiled. When a  file containing the include keyword is compiled, the named file is not  read in, parsed, and compiled initially. Only when that line of code  is executed is the file read, parsed and compiled. Only use the  require keyword if you know you will always need that named file in  the current script. If you might use its functions, use include  instead. PHP opens up all files that are required, but only opens  included files as needed. Additionally, you should also consider using  require_once and include_once in place of require and include  respectively. In practice, it is more likely that you actually want  the functionality provided by the require_once and include_once  functions, even though it is much more common to use the require and  include keywords respectively. Refer to the following PHP manual pages  for more information: include, include_once
source:  07001

翻譯自:https://stackoverflow.com/questions/14079459/include-external-php-files