开发者

PHP 5.3 and anonymous function default values?

开发者 https://www.devze.com 2023-04-03 16:48 出处:网络
In php 5.3, when you create an anonymous function, can you set the default values? Like in a normal functon you do

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 hav开发者_StackOverflow社区ing 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

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;
});


Yes you can set the default values like that


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消