我应该在我的示例中何时使用include require和require_once?

时间:2012-07-30 01:10:45

标签: php

  

可能重复:
  When should I use require_once vs include?

例如,如果我有:

header part(header.php)
footer part(footer.php)
list of functions (functions.php)
list of constants (constants.php)
connect to database part(connection.php)
footer part + close the connection part(footer.php)

在这些示例中,我应该使用includerequire还是require_once,请注意原因?

2 个答案:

答案 0 :(得分:8)

对于包含函数,类和其他实用程序的文件,通常需要require_once,这样就不会在多个库(或其他东西)中意外重新声明任何内容并破坏内容。

  • functions.php
  • constants.php
  • connection.php

对于您通常需要require的模板文件,因为它们应该能够多次包含而不会导致问题。 (不是说这可能是在这两个文件的特定情况下。)

  • header.php
  • footer.php

你永远不想*使用include(或include_once)。它就像require,但只在文件不存在时显示警告 - 可能不是预期的。

现在您注意到您的页脚关闭了数据库连接。您通常希望避免模板文件中的副作用。此外,可能不需要关闭数据库连接。 (鉴于你可以关闭它,这里有一些建议:改用PDO!)

答案 1 :(得分:1)

除非我特别需要多次包含文件(比如页面上多个地方的某个模板),否则我总是使用require_once。虽然在模板的情况下,使该模板成为可以具有多个实例的类将是更好的模式,因此该文件将仅包括在一次中。例如:

class TemplateExample() {
    function display() {
        echo "I'm a template!";
    }
}

$template = new TemplateExample();
$template->display();
echo "Some text between the templates.";
$template->display();

还值得注意的是,有一些消息来源表示不使用require_onceinclude_once因为它们比requireinclude慢。虽然它们确实较慢,但并不明显;在你的脚本减慢一毫秒之前,需要大约10,000个包含的内容。这种差异非常小,你不必担心速度。