9

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 the function as local and to be forgotten of when a returns? I need the function to pass it to array_filter.

kenorb
  • 137,499
  • 74
  • 643
  • 694
Daniel
  • 29,121
  • 15
  • 79
  • 134

4 Answers4

9

The idea of "local function" is also named "function inside function" or "nested function"... The clue was in this page, anonymous function, cited by @ceejayoz and @Nexerus, but, let's explain!

  1. In PHP only exist global scope for function declarations;
  2. The only alternative is to use another kind of function, the anonymous one.

Explaining by the examples:

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

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

PS: is not possible in PHP to declare a "static reference", the anonymous function will be never static.

See also:

Community
  • 1
  • 1
Peter Krauss
  • 12,407
  • 21
  • 149
  • 275
8

You could use an anonymous function in your array_filter call.

ceejayoz
  • 171,474
  • 40
  • 284
  • 355
3

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

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

This method doesn't require PHP 5.3+

Nexerus
  • 1,088
  • 7
  • 8
1

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

Check the following example:

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

a();
a();

Alternatively by checking if function already exists:

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

a();
a();
kenorb
  • 137,499
  • 74
  • 643
  • 694