致命的php错误:`使用include_once时不能重新声明函数`[复制]

致命的php错误:`使用include_once时不能重新声明函数`[复制]

问题描述:

This question already has an answer here:

I have a helper function helper.php with contents:

<?php
session_start();

function get_result($dbh, $sql) {
    //return mssql_query($sql);
    return $dbh->query($sql);
}
?>

which is included in two files (information.php and commercial.php) using:

include_once 'helper.php'

Unfortunately this generates the slightly confusing error message:

PHP Fatal error:  Cannot redeclare get_result() (previously declared in helper.php:4) in helper.php on line 4

I understand that i cannot redeclare functions, hence why i use the include_once construct, but nevertheless it tries to redeclare the function anyway. Why?

If it helps; I am using Mustache PHP, and all three files are located in the partials folder.

</div>

此问题已经存在 这里有一个答案: p>

  • ”致命错误:无法重新声明&lt; function&gt;“ 14 answers span> li> ul> div>

    我有一个辅助函数 helper.php code>,内容为:

     &lt;?php 
    session_start(); 
     
    function get_result($ dbh,$ sql){
     // return mssql_query($ sql); 
     return $  dbh-&gt;查询($ sql); 
    } 
    ?&gt; 
      code>  pre> 
     
     

    它包含在两个文件中( information.php 代码>和 commercial.php code>)使用: p>

      include_once'helper.php'
      code>  pre> 
     
      

    不幸的是,这会产生稍微混乱的错误消息: p> \ n

      PHP致命错误:无法在第4行的helper.php中重新声明get_result()(先前在helper.php:4中声明)
      code>  pre> 
     
     我明白我不能重新声明函数,因此我使用 include_once  code>构造的原因,但是它仍尝试重新声明函数。 为什么? p> 
     
     

    如果有帮助; 我使用的是Mustache PHP,并且所有三个文件都位于 partials code>文件夹中。 p> div>

include_once ensures that file is included exactly once. It doesn't check the contents of the file or the functions in it. So when two file with same function name is added, its quite natural for the error to arise!

From the manual:

include_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

italicized means that the function in the same file, not in different files.

One way to get around this error is to wrap your helper functions in a check.

You could try something like:

if (! function_exists('get_result')) {

    function get_result()
    {
        //your code
    }
}

Hope this helps!