PHP 5.6 Every time I write a local function (a function inside another function), I get a "cannot redeclare" error. What is the problem? This is a local function. What the hell is the redefinition? For example:

class A { public function foo($x) { function bar($n) { return $n * 2; } return bar($x); } } $a = new A(); var_dump($a->foo(2), $a->foo(3)); 

You can check here .

  • call one method var_dump ($ a-> foo (2)); - Arsen
  • @Arsen, um, why would? Why can't I call the method twice? : D - PECHAPTER

2 answers 2

Try writing a function to a variable.

 class A { public function foo($x) { $localFunction = function($n) { return $n * 2; }; return $localFunction($x); } } $a = new A(); var_dump($a->foo(2), $a->foo(3)); 
  • Still, it is very illogical ... Redefinition is when the same function is described twice in different places. I would say all the same that it is a language bug. The function code does not change from call to call. Those. it turns out that local functions in the language are, as it were, but they cannot be used in principle. - PECHAPTER
  • I would prefer that, in principle, throwing an error to local functions right away and the IDE highlighting. In order not to be misleading. (well, or change the behavior to work as it should) - PECHAPPER
  • Nothing contradicts. In python, there are local functions and recently even entered into C #. And nothing! Does not bother anyone. It is simply useful to sometimes encapsulate fine logic used in only one function into a separate function, which, for example, can then be passed to some sort of array_map, or just called several times. - PECHAPTER
  • @DarkByte found a solution to your problem, corrected the answer - Sasha Borichevsky
  • one
    if you write a function into a variable, it will be an anonymous function. The author has a question about named global functions. This is an alternative option, but does not answer the question. - teran

PCP tells you exactly what is happening. Take a closer look at the logic of your code. Your class method defines a new bar function. Here you called it once - determined. Now you call it a second time - and again it tries to determine the function bar , which was already defined in the global scope at the previous call. So the error message is quite correct function should be defined only once. (for analogy, you can compare with the definition of constants)

To avoid such a situation, you need to check in one way or another whether a function has already been defined; the simplest thing here is to use function_exists()

 class A { public function foo($x) { if(!function_exists('bar')){ function bar($n) { return $n * 2; } } return bar($x); } } 

In this case, the method will be determined only at the first call.