Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define local functions in PHP?

Tags:

function

php

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.

like image 564
Dani Avatar asked Sep 19 '11 00:09

Dani


People also ask

How do you define a function in PHP?

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.

How do you define a function in PHP give an example?

//define a function function myfunction($arg1, $arg2, ... $argn) { statement1; statement2; .. .. return $val; } //call function $ret=myfunction($arg1, $arg2, ... $argn);

What is necessary to declare a variable to be local to a function in PHP?

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.

Which is the correct way to create a function in PHP?

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 {}.


1 Answers

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?
like image 122
5 revs, 2 users 84% Avatar answered Oct 04 '22 20:10

5 revs, 2 users 84%