开发者

How to define local functions in PHP?

When I try to do this:

fu开发者_开发知识库nction 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.


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:

  • var functionName = function() {} vs function functionName() {} (ans)
  • What are PHP nested functions for?


You could use an anonymous function in your array_filter call.


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+


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜