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?
$ php -r '$foo = function($a = 123){echo $a, PHP_EOL;};$foo(1);$foo();'
1
123
So that's a yes
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;
});
Yes you can set the default values like that
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