include_once或require_once解决了哪些问题?

时间:2013-01-19 22:19:37

标签: php include

来自php手册

  

Include_once可以帮助避免诸如功能重新定义,变量值重新分配等问题。

好的,所以include_once解决了功能重新定义,变量值重新分配等问题,但为什么它们首先成为问题呢?

我试图了解重新定义函数或重新分配变量值所涉及的风险类型,除了由于额外的输入/输出和处理导致的性能下降之外?

是因为php解析器混淆了加载/使用哪个版本的函数,还是重新定义后丢失的函数的原始版本?还有什么可变的重新分配?

我确实知道在哪里使用include vs include_once

3 个答案:

答案 0 :(得分:4)

想象一下以下包含文件hello.php

function hello()
{
    return 'Hello World';
}

$a = 0;

现在想象一下以下文件index.php

include 'hello.php';

$a = 1;
hello();

include 'hello.php';

hello();
echo $a; // $a = 0, not 1

您的代码现在会出现致命错误,因为该函数已定义两次。使用include_once可以避免这种情况,因为它只包含hello.php一次。此外,与variable value reassignment$a(如果代码编译)将重置为0。


从评论中,请考虑这是一个侧面答案 - 如果您正在寻找需要多次重置一组变量 的东西,我会看要使用像Reset之类的方法来使用类,如果你不想实例化它,你甚至可以将它设置为静态,如下所示:

public class MyVariables
{
    public static $MyVariable = "Hello";
    public static $AnotherVariable = 5;

    public static function Reset()
    {
        self::$MyVariable = "Hello";
        self::$AnotherVariable = 5;
    }
}

用法如:

MyVariables::$MyVariable = "Goodbye";
MyVariables::Reset();
echo MyVariables::$MyVariable; // Hello

答案 1 :(得分:1)

假设您有一个包含脚本vars.inc.php:

<?php

    $firstname = 'Mike';
    $lastname = 'Smith';

?>

然后你有一个脚本script.php:

<?php

    echo "$firstname $lastname"; // no output

    include('vars.inc.php');
    echo "$firstname $lastname"; // Mike Smith

    $firstname = "Tim";
    $lastname = "Young"; 
    echo "$firstname $lastname"; // Tim Young

    include('vars.inc.php');
    echo "$firstname $lastname"; // Mike Smith
?>

如果您在代码执行中修改vars,然后再次包含定义它们的文件,那么您将更改其内容。 include_once将确保永远不会发生错误。

答案 2 :(得分:0)

它将阻止您多次加载页面。通常,您将在页面顶部使用它来引入init,函数,类文件等。

如果您在页面中动态加载页面,则特别有用。

相关问题