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
  • 155,785
  • 88
  • 678
  • 743
Daniel
  • 30,896
  • 18
  • 85
  • 139

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
  • 13,174
  • 24
  • 167
  • 304
8

You could use an anonymous function in your array_filter call.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
3

Warning for PHP 7.2 or above!

create_function is deprecated in php 7.2 and removed in php 8+.

This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

Replaced by: https://www.php.net/manual/en/functions.anonymous.php


Original answer:

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+

brunoais
  • 6,258
  • 8
  • 39
  • 59
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
  • 155,785
  • 88
  • 678
  • 743