dronthpi05943 2013-01-19 22:19
浏览 64
已采纳

include_once或require_once解决了哪些问题?

From the php manual

Include_once may help avoid problems such as function redefinitions, variable value reassignments, etc.

Ok, so include_once solves issues with function redefinitions, variable value reassignments, etc. but why are they an issue in the first place ?

I'm trying to understand what kind of risks are involved in redefining functions or reassigning variable values except for a decline in performance due to additional input/output and processing ?

Is it because php parser gets confused which version of function to load/use or is the original version of the function lost once redefined? What else and what about variable reassignments?

I do understand where to use include vs include_once.

  • 写回答

3条回答 默认 最新

  • doumu5023 2013-01-19 22:21
    关注

    Imagine the following include file, hello.php:

    function hello()
    {
        return 'Hello World';
    }
    
    $a = 0;
    

    Now imagine the following file, index.php:

    include 'hello.php';
    
    $a = 1;
    hello();
    
    include 'hello.php';
    
    hello();
    echo $a; // $a = 0, not 1
    

    Your code would now have a fatal error, since the function has been defined twice. Using include_once would avert this, since it would only include hello.php once. Also, to do with variable value reassignment, $a (should the code compile) would be reset to 0.


    From the comments, please consider this a side answer - If you're looking for something where resetting a set of variables many times was required, I'd look to use a class for this with a method like Reset, you can even make it static if you didn't want to have to instantiate it, like so:

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

    Usage like:

    MyVariables::$MyVariable = "Goodbye";
    MyVariables::Reset();
    echo MyVariables::$MyVariable; // Hello
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序