drruhc4944 2017-04-12 08:59
浏览 22
已采纳

PHP优先级函数声明

I have a question on the way that functions are declared in PHP.

First test :

File "functions.php" => functions toto(){ return "1"; }

Main File


    include("functions.php")
    functions toto(){ return "main"; }
    echo toto();

Second test

File "functions.php" => functions toto(){ return "1"; }

File "functions2.php" => functions toto(){ return "2"; }

Main File


    include("functions.php")
    include("functions2.php")
    echo toto();

Results

The first test work and echo "main"
The second test doesn't work => fatal error "function toto already define"
I make complementary tests :

  • in first test : put the functions toto() before include doesn't change the result.
  • Create twice functions toto() in the main file create Fatal Error


Someone can explain me how exactly this work ?
Thanks for reading

  • 写回答

2条回答 默认 最新

  • doufenyu7610 2017-04-12 09:24
    关注

    The PHP statements from the include family do not copy-paste the content of the included file in the context of the includer. The inclusion happens at runtime.

    In your first example, the function toto() defined in the main file is created during the compilation. Then, on the execution, the functions.php file is read and parsed. It generates an error because it attempts to define the function toto() that is already defined.

    The same happens in the second example during the inclusion of functions.php. Also, you get the same error if you declare the function toto() two times in the main script.

    Either way, the PHP functions and constants cannot be re-declared. A quick quote from the documentation:

    PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

    You can check if a function is already defined (to avoid defining it again) by using the function_exists() PHP function:

    function toto() { return 1; }
    
    if (! function_exists('toto')) {
        function toto() { return 2; }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀