简体   繁体   English

PHP无法重新声明功能

[英]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 但我收到此错误,无法重新声明calcPercentages(),它告诉我它在第17行声明是正确的

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 除了auditStats函数内部以外,没有在任何地方调用该函数,并且使用以下方法在页面的更下方调用结果

$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. 如果我犯了一个明显的新手错误,请原谅,我正在从程序性转向OOP,并且刚开始。

You declare calcPercentages inside the auditStats function, so it gets re-declared every time you call auditStats . 您在auditStats函数内声明calcPercentages ,因此每次调用auditStats时都会重新声明它。

Move calcPercentages outside of auditStats . 移动calcPercentages之外auditStats

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 . 在PHP中,与JS不同,一个函数永远不会局部存在于另一个函数中,因此,当到达行function calcPercentages...时,您将创建一个名为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 . 要么将声明全局移出外部,要么将其放入类或对象中,要么使它成为匿名函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM