Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.3 and anonymous function default values?

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?

like image 318
cwd Avatar asked Aug 02 '26 14:08

cwd


2 Answers

$ 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;
});
like image 144
Phil Avatar answered Aug 04 '26 03:08

Phil


Yes you can set the default values like that

like image 38
Roshan Wijesena Avatar answered Aug 04 '26 04:08

Roshan Wijesena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!