Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function inside function in php: error: Cannot redeclare [duplicate]

I have this php script:

function hoeveelzijner ($jaar, $id)
{
            function hoeveelhoeveel($beginstamp, $endstamp, $id)
            {
                $dates = mysql_query('SELECT v_date FROM visitors WHERE id="'.$id.'" AND v_date<"'.$endstamp.'" AND v_date>"'.$beginstamp.'"');
                return mysql_num_rows($dates);
            }
$i = 1;
while ($i < 13)
{
    $hoeveel[$i-1] = hoeveelhoeveel(mktime(0, 0, 0, $i, 1, $jaar),mktime(0, 0, 0, $i, cal_days_in_month(CAL_GREGORIAN,$i,$jaar),$jaar),$id);
    $i = $i+1;
}
return $hoeveel;
}

When I put this beneath it, it works just fine:

$values = hoeveelzijner(2005, 1);

However, when I do it twice, for example:

$values = hoeveelzijner(2005, 1);
$test = hoeveelzijner(2000, 4);

I get this error: Fatal error: Cannot redeclare hoeveelhoeveel() (previously declared in ...:69) in ... on line 69.

Anyone knows what I am doing wrong? It kinda destroys the purpose of using functions if I can only use it once...

Extra info: I do not include any other files, nor do I redeclare the function somewhere else in the script.

Thanks a lot!

like image 563
binoculars Avatar asked Sep 25 '11 11:09

binoculars


1 Answers

You can't only use it once; you can only declare it once. Every time the function hoeveelzijner is used, the function hoeveelhoeveel is declared. If you call it more than once, you'll redeclare it, which is forbidden.

You have two options: the first is to take the function definition outside the containing function. The function will be declared when the file is first parsed, then used repeatedly. If you want to restrict the function definition to a particular scope (a good idea in principle), you can use the anonymous function syntax introduced in PHP 5.3:

function hoeveelzigner($jaar, $id)
{
    $hoeveelhoeveel = function($beginstamp, $endstamp, $id)
    {
            $dates = mysql_query('SELECT v_date FROM visitors WHERE id="'.$id.'" AND v_date<"'.$endstamp.'" AND v_date>"'.$beginstamp.'"');
            return mysql_num_rows($dates);
    };

    // etc
}

You can then use the function as $hoeveelhoeveel(...).

like image 127
lonesomeday Avatar answered Nov 09 '22 02:11

lonesomeday