素材牛VIP会员
有关php函数定义的问题
 d***悠  分类:PHP代码  人气:913  回帖:1  发布于6年前 收藏

今天在使用Kirby(一种cms)时,碰到了下面的代码:

$events = page('events') ->children() ->visible() ->filter(function($child) { return $child->date(null, 'startdate') > time() && $child->date(null, 'enddate') < time(); });

请问方法(filter())内定义新函数是什么写法,有什么用途?(请举例说明)谢谢!

 标签:php

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv5 码农
38***38 职业无 6年前#1

参见:http://php.net/manual/zh/func...

这是匿名函数,主要用处是不用额外声明一个函数防止污染外部变量,以上语句一定情况下等价于:

$anonymous_function = function($child) {
    return $child->date(null, 'startdate') > time() && $child->date(null, 'enddate') < time();
};
$events = page('events')->children()->visible()->filter($anonymous_function($child));

但是,这样$anonymous_function就会覆盖外部原有的$anonymous_function值(如果有的话),也就是污染外部变量。

具体例子参见PHP文档。

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取