tatty27
tatty27

Reputation: 1554

Php can't redeclare function

as far as I can tell the function is only declared once . but I get this error Cannot redeclare calcPercentages() and it tells me it was declared on line 17 which is correct

the function that contains the errant function...

function auditStats($audit){

    $mysqli = dbConnect();
    $audit_id = $audit;
    $result = $mysqli->query("SELECT imageGrade, SUM(imageGrade=1) AS grade1, SUM(imageGrade=2) AS grade2, SUM(imageGrade=3) AS grade3, COUNT(*) AS total_imgs FROM image WHERE type != 'standard' and auditID ='$audit_id'")or exit("Error code ({$mysqli->errno}): {$mysqli->error}");
    $row = $result->fetch_assoc();

    $grade1 = $row['grade1'];
    $grade2 = $row['grade2'];
    $grade3 = $row['grade3'];
    $totalImgs = $row['total_imgs'];

    function calcPercentages($grade, $total){
        $percent = round(($grade / $total) * 100,2);
        return $percent;
    }
    if ($totalImgs != 0){
        $percent_1 = calcPercentages($grade1, $totalImgs);
    }
    $return_array = [
        'total'=>$totalImgs,
        'percent_1'=>$percent_1
    ];
    return $return_array;
}

The function isn't being called anywhere except within the auditStats function and the results are called further down the page using

$percent_1 = auditStats($auditID)[percent_1];

Please excuse me if I have made on obvious newbie error, I am moving from procedural to OOP and am just starting out with it.

Upvotes: 1

Views: 170

Answers (2)

IMSoP
IMSoP

Reputation: 97977

In PHP, unlike say JS, a function is never local to another function, so when the line function calcPercentages... is reached, you're creating a global function called calcPercentages. When it's run again, you're trying to create another global function with the same name, and you get the error.

Either move the declaration outside globally, put it in a class or object or make an anonymous function.

Upvotes: 2

scrowler
scrowler

Reputation: 24425

You declare calcPercentages inside the auditStats function, so it gets re-declared every time you call auditStats.

Move calcPercentages outside of auditStats.

Upvotes: 6

Related Questions