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
.
A function is a piece of code that takes another input in the form of a parameter, processes it, and then returns a value. A PHP Function feature is a piece of code that can be used over and over again and accepts argument lists as input, and returns a value. PHP comes with thousands of built-in features.
//define a function function myfunction($arg1, $arg2, ... $argn) { statement1; statement2; .. .. return $val; } //call function $ret=myfunction($arg1, $arg2, ... $argn);
PHP defines a variable on its first use. There is no keyword for declaring a local scope. All variables inside functions are local by default (even a variable with the same name as another global variable). 'A first use' means assigning a value, not using the variable in return or a condition.
The declaration of a user-defined function starts with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}.
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!
Explaining by the examples:
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() {}
.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With