How to define local functions in PHP?

When I try to do this:

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

I get Cannot redeclare b...
When I tried to do this:

 function a() { if(!isset(b)) function b() { } } a(); a(); 

I get unexpected ), expected ...
How can I declare a function as local and forget when a returns? I need a function to pass it to array_filter .

+6
source share
4 answers

You can use an anonymous function in your array_filter call.

+7
source

The idea of ​​a "local function" is also called a "function inside a function" or " nested function " ... The tip was on this page, an anonymous function quoted by @ceejayoz and @Nexerus, but explain!

  • In PHP, there is only a global scope for function declarations ;
  • The only alternative is to use another type of function - anonymous.

Explanation by examples:

  • function b() in function a(){ function b() {} return b(); } function a(){ function b() {} return b(); } also global, so the declaration has the same effect as function a(){ return b(); } function b() {} function a(){ return b(); } function b() {} .

  • To declare something like "function b () in scope ()," the only alternative is to use not $b() , but a link. The syntax will be similar to function a(){ $b = function() { }; return $b(); } function a(){ $b = function() { }; return $b(); }

PS: it is impossible to declare a "static link" in PHP, an anonymous function will never be static.

See also:

+5
source

You can try the create_function PHP function. http://php.net/create_function

 $myfunc = create_function(..., ...); array_filter(..., $myfunc(...)); unset($myfunc); 

This method does not require PHP 5.3+

+3
source

You can define a local function in PHP, but you can only declare it once. This can be achieved by defining and comparing a static variable.

See the following example:

 <?php function a() { static $init = true; if ($init) { function b() { } $init = FALSE; } } a(); a(); 

Alternatively, by checking if a function exists:

 <?php function a() { if (!function_exists('b')) { function b() { } } } a(); a(); 
0
source

Source: https://habr.com/ru/post/897581/


All Articles