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...
.
function a()
{
if(!isset(b))
function b() { }
}
a();
a();
I get unexpected ), expected ...
.
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!
- In PHP only exist global scope for function declarations;
- The only alternative is to use another kind of function, the anonymous one.
Explaining by the examples:
the function
b()
infunction a(){ function b() {} return b(); }
is also global, so the declaration have the same effect asfunction a(){ return b(); } function b() {}
.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 likefunction 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();
精彩评论