2

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.

nluigi
  • 1,263
  • 2
  • 15
  • 35
  • What are the contents of `helper.php`? You showed the contents of `help.php`. Also, are you sure that every inclusion of `helper.php` is done through `include_once`? – Daan Meijer Jan 04 '17 at 10:42
  • @DaanMeijer - sorry it was a typo, it should be `helper.php`. fixed! – nluigi Jan 04 '17 at 10:51
  • Great :) Now, my other question: are you sure that every inclusion is through `include_once`? – Daan Meijer Jan 04 '17 at 10:55
  • @DaanMeijer - yes – nluigi Jan 04 '17 at 10:56
  • Then you might have stumbled on a bug in PHP ;) Or, you might have missed an `include` statement. You can debug this by putting `debug_print_backtrace();` in your `helper.php`. Should show you which file included `helper.php`. – Daan Meijer Jan 04 '17 at 10:58
  • @DaanMeijer - i will check that out when i have a bit more time on my hands to properly figure out this problem.thx – nluigi Jan 04 '17 at 11:00

2 Answers2

2

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.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • Accepting this as the answer because it answers my actual question (why this happens?) the best – nluigi Jan 04 '17 at 10:59
2

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!

Rwd
  • 34,180
  • 6
  • 64
  • 78
  • I used this to get around the redeclaration, but it seems like a quick fix to me... I am content with it for now as it helps the problem and i am on a bit of a deadline but i will revisit this in the future and see if i can do this without resorting to a 'fix' – nluigi Jan 04 '17 at 10:58