有关php函数定义的问题

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

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

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

阅读 1.9k
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文档。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题