3

In php 5.3, when you create an anonymous function, can you set the default values?

Like in a normal functon you do

function tim($a=123){

}

where 123 is the default value for $a. What abut in anonymous functions?

UPDATE

I'm having trouble with it in this context:

//$data is an object;
$data->title = 'test';
add_filter('title',function($current, $new = $data->title ){ return $new; });

produces "unexpected T_VARIABLE"

works fine without the $data->title bit, but I really want to pass this in...

add_filter('title',function($current, $new = 'some-title' ){ return $new; });

I'm adding a filter in Wordpress. Works fine if I explicitly set it, but I want to pull it from another variable. Is that possible?

4 Answers 4

10
$ php -r '$foo = function($a = 123){echo $a, PHP_EOL;};$foo(1);$foo();'
1
123

So that's a yes

Update

You can only assign simple values to argument defaults. From the manual

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Try passing the external variable via the use keyword

add_filter('title', function($current, $new = null) use ($data) {
    if (null === $new) {
        $new = $data->title;
    }
    return $new;
});
Sign up to request clarification or add additional context in comments.

3 Comments

i'm having trouble with this for some reason. let me see if I can get it.
perfect! didn't know that "use" existed! :)
You could use my tiny library ValueResolver in this case
1

Yes you can set the default values like that

Comments

0

Here's an example of using an anonymous function in PHP from the PHP website.

<?php
echo preg_replace_callback(
  '~-([a-z])~',
  function ($match) {
    return strtoupper($match[1]);
  },
  'hello-world'
);

See the function ($match) { part? You can define the in there like any other function.

Comments

0

You could use my tiny library ValueResolver in this case, for example:

add_filter('title', function($current, $new = null) use ($data) {
    return ValueResolver::resolve($new, $data->title);
});

and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

There are also ability to typecasting, for example if your variable's value should be integer, so use this:

$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)

Check the docs for more examples

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.