2011-03-31 111 views
3

我知道PHP 5.3引入的功能,如lambda表达式,但我坚持以前的版本(5.2)。PHP的功能风格

是否有任何库向PHP添加功能性功能? PHP数组有一些map/reduce/filter函数,但我很想看看是否还有更多。

此外,我知道PHPLinq模仿.NET的LINQ,但我没有试一试。

感谢

+3

究竟做ü希望能够做什么? – Neal 2011-03-31 18:47:36

+0

你需要更具体。你在寻找什么功能?没有支持类lambda表达式的库,因为这是解析器本身内部的语法语言功能。 – Unsigned 2011-03-31 18:49:29

回答

3

根据PHP文档,PHP 4.0.1和PHP 5有以下方法来创建拉姆达式功能:

http://php.net/manual/en/function.create-function.php

+0

它的类似但不是真正的lambda表达式,它更多的是延迟eval()。他提到的表达式在语法上也是不兼容的。 – Unsigned 2011-03-31 19:02:37

+1

是的。就像你说的那样,它必须是语言和解释器/编译器的一部分,才是他正在寻找的东西。这是......不完美的东西。 :) – 2011-03-31 19:15:08

+0

create_function()是痛苦的,但据我所知,PHP 5.2所提供的最好。 – Waquo 2011-04-03 12:09:18

0

以防万一,人们仍有兴趣这样的库,请查看Saber功能PHP库。

1

Non-stardard PHP library (NSPL)使得使用PHP编写功能代码更容易。看看与NSPL写下面的代码:

// get user ids 
$userIds = map(propertyGetter('id'), $users); 

// or sort them by age 
$sortedByAge = sorted($users, methodCaller('getAge')); 

// or check if they all are online 
$online = all($users, methodCaller('isOnline')); 

// or define new function as composition of the existing ones 
$flatMap = compose(rpartial(flatten, 1), map); 

在纯PHP就应该是这样的:

// get user ids 
$userIds = array_map(function($user) { return $user->id; }, $users); 

// sort them by age, note that the following code modifies the original users array 
usort($users, function($user1, $user2) { 
    return $user1->getAge() - $user2->getAge(); 
}); 

// check if they all are online 
$online = true; 
foreach ($users as $user) { 
    if (!$user->isOnline()) { 
     $online = false; 
     break; 
    } 
} 

// define new function as composition of the existing ones 
$flatMap = function($function, $list) { 
    // note the inconsistency in array_map and array_reduce parameters 
    return array_reduce(array_map($function, $list), 'array_merge', []); 
};