Why does everything work normally with a single use, but if you call a function twice, everything breaks?

$arr1 = [1, 2, 3, 4]; $arr2 = [3, 2, 2, 1, 0, 6, 1]; $arr3 = [1, 3, 2, 1, 5, 4, 1]; function rob($ar){ function fun($arr, $acc = 0) { if(max($arr) == null) { return $acc; } else { $acc = $acc + max($arr); $key = array_search(max($arr), $arr); if ($key === 0) { $arr[$key] = null; $arr[$key + 1] = null; return fun($arr, $acc); } elseif ($key === (count($arr) - 1)) { $arr[$key] = null; $arr[$key - 1] = null; return fun($arr, $acc); } else { $arr[$key] = null; $arr[$key + 1] = null; $arr[$key - 1] = null; return fun($arr, $acc); } } } // return $a = fun($ar); return $a; } echo rob($arr1)."\n"; echo rob($arr2)."\n"; echo rob($arr3)."\n"; 

    2 answers 2

    What you are doing is not a closure. In fact, you simply define the fun function inside rob and get what you expect:

    PHP Fatal error: Cannot redeclare fun () (previously declared in ...

    The correct code can be:

     $arr1 = [1, 2, 3, 4]; $arr2 = [3, 2, 2, 1, 0, 6, 1]; $arr3 = [1, 3, 2, 1, 5, 4, 1]; function fun($arr, $acc = 0) { // ... } function rob($ar) { // Понятия не имею, зачем вам нужна эта функция-обертка return fun($ar); } echo rob($arr1)."\n"; // 6 echo rob($arr2)."\n"; // 11 echo rob($arr3)."\n"; // 9 

    Working Example on IDE One

    • I originally wrote this, and this option also did not work as it should, and gave the same errors ... - arseniy mironov
    • one
      I gave you a link to ideone and everything works there. If something does not work for you, then start by updating the question and adding an error message there. Otherwise, all this is fortune telling. - Dmitriy Simushev

    All PHP functions and classes have a global scope - they can be called outside the function, even if they were defined internally and vice versa.

    PHP does not support function overloading; it is also not possible to override or delete a function declared earlier.

    http://php.net/manual/ru/functions.user-defined.php

    This means that the only difference between

     function a(){ function b(){}; }; 

    and

     function a(){}; function b(){}; 

    only that the function b in the first case cannot be used before the call of the function a , and the repeated call of the function a will cause an error

    Fatal error: Cannot redeclare ....


    Two solutions:

    1. Once declare fun outside rob
    2. Use anonymous functions $fun = function(){...}
    • I tried through anonymous functions, also failed. And thanks to all for the answers) - arseniy mironov