2

I have a function, which I'd like to pass as an argument to multiple functions. Is there a way to do this with anonymous functions, in one 'line'.

This is what it looks like without an anonymous function:

function my_function( $input ) {
    return $input;
}

add_filter( 'filter_one', 'my_function' );
add_filter( 'filter_two', 'my_function' );

Here's what calling add_filter once with the anonymous setup would look like:

add_filter( 'filter_one', function ( $input ) {
        return $input;
});

Does the syntax exist in PHP to do the same for filter_two without re-writing the function that's the argument?

8
  • 1
    What's wrong with actually defining the function? If you don't want to have it globally available, define it inside another function to limit the scope. Commented Jun 4, 2018 at 10:28
  • Nothing wrong with it, I'm just interested to know if there is a way to do it Commented Jun 4, 2018 at 10:29
  • 2
    @AleksG - you don't get any Hipster Beard points going around doing something as old-skool as actually defining function names... Commented Jun 4, 2018 at 10:29
  • @AleksG You can't limit the scope of a function in PHP; you may be thinking of JavaScript, where functions have the same scoping rules as variables. In PHP, a function is global, scoped to a namespace, or is a method or static method of some class. An anonymous function, however, is scoped, in that it's a value that can be passed around. Commented Jun 4, 2018 at 10:29
  • @CD001 You also don't get the ability to dynamically define ("close over") variables when the function is created; or the ability to know that the function is not callable from any other scope; or the ability to keep code concise by having it in one flow rather than needing to jump out to a separate definition of a two-line function. But sure, if hipster beard points are your thing, feel free to stay proud that your code will run under PHP 4. Commented Jun 4, 2018 at 10:37

1 Answer 1

3

While often defined inline as a parameter to some function, an anoymous function is just a value which can be used like any other. (To be precise, it is a Closure object.)

So you can assign your callback to a variable, and pass that variable around wherever you like:

$noop = function ( $input ) {
        return $input;
};
add_filter( 'filter_one', $noop );
add_filter( 'filter_two', $noop );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.